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/Instructions.h"
18 #include "llvm/Module.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Assembly/AutoUpgrade.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/MathExtras.h"
29 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
30 int yylex(); // declaration" of xxx warnings.
34 std::string CurFilename;
38 static Module *ParserResult;
40 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
41 // relating to upreferences in the input stream.
43 //#define DEBUG_UPREFS 1
45 #define UR_OUT(X) std::cerr << X
50 #define YYERROR_VERBOSE 1
52 static bool ObsoleteVarArgs;
53 static bool NewVarArgs;
54 static BasicBlock *CurBB;
55 static GlobalVariable *CurGV;
58 // This contains info used when building the body of a function. It is
59 // destroyed when the function is completed.
61 typedef std::vector<Value *> ValueList; // Numbered defs
63 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
64 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
66 static struct PerModuleInfo {
67 Module *CurrentModule;
68 std::map<const Type *, ValueList> Values; // Module level numbered definitions
69 std::map<const Type *,ValueList> LateResolveValues;
70 std::vector<PATypeHolder> Types;
71 std::map<ValID, PATypeHolder> LateResolveTypes;
73 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
74 /// how they were referenced and one which line of the input they came from so
75 /// that we can resolve them later and print error messages as appropriate.
76 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
78 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
79 // references to global values. Global values may be referenced before they
80 // are defined, and if so, the temporary object that they represent is held
81 // here. This is used for forward references of GlobalValues.
83 typedef std::map<std::pair<const PointerType *,
84 ValID>, GlobalValue*> GlobalRefsType;
85 GlobalRefsType GlobalRefs;
88 // If we could not resolve some functions at function compilation time
89 // (calls to functions before they are defined), resolve them now... Types
90 // are resolved when the constant pool has been completely parsed.
92 ResolveDefinitions(LateResolveValues);
94 // Check to make sure that all global value forward references have been
97 if (!GlobalRefs.empty()) {
98 std::string UndefinedReferences = "Unresolved global references exist:\n";
100 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
102 UndefinedReferences += " " + I->first.first->getDescription() + " " +
103 I->first.second.getName() + "\n";
105 ThrowException(UndefinedReferences);
108 // Rename any overloaded intrinsic functions.
109 for (Module::iterator FI = CurrentModule->begin(), FE =
110 CurrentModule->end(); FI != FE; ++FI)
111 UpgradeIntrinsicFunction(&(*FI));
113 Values.clear(); // Clear out function local definitions
118 // GetForwardRefForGlobal - Check to see if there is a forward reference
119 // for this global. If so, remove it from the GlobalRefs map and return it.
120 // If not, just return null.
121 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
122 // Check to see if there is a forward reference to this global variable...
123 // if there is, eliminate it and patch the reference to use the new def'n.
124 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
125 GlobalValue *Ret = 0;
126 if (I != GlobalRefs.end()) {
134 static struct PerFunctionInfo {
135 Function *CurrentFunction; // Pointer to current function being created
137 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
138 std::map<const Type*, ValueList> LateResolveValues;
139 bool isDeclare; // Is this function a forward declararation?
141 /// BBForwardRefs - When we see forward references to basic blocks, keep
142 /// track of them here.
143 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
144 std::vector<BasicBlock*> NumberedBlocks;
147 inline PerFunctionInfo() {
152 inline void FunctionStart(Function *M) {
157 void FunctionDone() {
158 NumberedBlocks.clear();
160 // Any forward referenced blocks left?
161 if (!BBForwardRefs.empty())
162 ThrowException("Undefined reference to label " +
163 BBForwardRefs.begin()->first->getName());
165 // Resolve all forward references now.
166 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
168 Values.clear(); // Clear out function local definitions
172 } CurFun; // Info for the current function...
174 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
177 //===----------------------------------------------------------------------===//
178 // Code to handle definitions of all the types
179 //===----------------------------------------------------------------------===//
181 static int InsertValue(Value *V,
182 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
183 if (V->hasName()) return -1; // Is this a numbered definition?
185 // Yes, insert the value into the value table...
186 ValueList &List = ValueTab[V->getType()];
188 return List.size()-1;
191 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
193 case ValID::NumberVal: // Is it a numbered definition?
194 // Module constants occupy the lowest numbered slots...
195 if ((unsigned)D.Num < CurModule.Types.size())
196 return CurModule.Types[(unsigned)D.Num];
198 case ValID::NameVal: // Is it a named definition?
199 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
200 D.destroy(); // Free old strdup'd memory...
205 ThrowException("Internal parser error: Invalid symbol type reference!");
208 // If we reached here, we referenced either a symbol that we don't know about
209 // or an id number that hasn't been read yet. We may be referencing something
210 // forward, so just create an entry to be resolved later and get to it...
212 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
215 if (inFunctionScope()) {
216 if (D.Type == ValID::NameVal)
217 ThrowException("Reference to an undefined type: '" + D.getName() + "'");
219 ThrowException("Reference to an undefined type: #" + itostr(D.Num));
222 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
223 if (I != CurModule.LateResolveTypes.end())
226 Type *Typ = OpaqueType::get();
227 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
231 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
232 SymbolTable &SymTab =
233 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
234 CurModule.CurrentModule->getSymbolTable();
235 return SymTab.lookup(Ty, Name);
238 // getValNonImprovising - Look up the value specified by the provided type and
239 // the provided ValID. If the value exists and has already been defined, return
240 // it. Otherwise return null.
242 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
243 if (isa<FunctionType>(Ty))
244 ThrowException("Functions are not values and "
245 "must be referenced as pointers");
248 case ValID::NumberVal: { // Is it a numbered definition?
249 unsigned Num = (unsigned)D.Num;
251 // Module constants occupy the lowest numbered slots...
252 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
253 if (VI != CurModule.Values.end()) {
254 if (Num < VI->second.size())
255 return VI->second[Num];
256 Num -= VI->second.size();
259 // Make sure that our type is within bounds
260 VI = CurFun.Values.find(Ty);
261 if (VI == CurFun.Values.end()) return 0;
263 // Check that the number is within bounds...
264 if (VI->second.size() <= Num) return 0;
266 return VI->second[Num];
269 case ValID::NameVal: { // Is it a named definition?
270 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
271 if (N == 0) return 0;
273 D.destroy(); // Free old strdup'd memory...
277 // Check to make sure that "Ty" is an integral type, and that our
278 // value will fit into the specified type...
279 case ValID::ConstSIntVal: // Is it a constant pool reference??
280 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
281 ThrowException("Signed integral constant '" +
282 itostr(D.ConstPool64) + "' is invalid for type '" +
283 Ty->getDescription() + "'!");
284 return ConstantSInt::get(Ty, D.ConstPool64);
286 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
287 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
288 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
289 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
290 "' is invalid or out of range!");
291 } else { // This is really a signed reference. Transmogrify.
292 return ConstantSInt::get(Ty, D.ConstPool64);
295 return ConstantUInt::get(Ty, D.UConstPool64);
298 case ValID::ConstFPVal: // Is it a floating point const pool reference?
299 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
300 ThrowException("FP constant invalid for type!!");
301 return ConstantFP::get(Ty, D.ConstPoolFP);
303 case ValID::ConstNullVal: // Is it a null value?
304 if (!isa<PointerType>(Ty))
305 ThrowException("Cannot create a a non pointer null!");
306 return ConstantPointerNull::get(cast<PointerType>(Ty));
308 case ValID::ConstUndefVal: // Is it an undef value?
309 return UndefValue::get(Ty);
311 case ValID::ConstZeroVal: // Is it a zero value?
312 return Constant::getNullValue(Ty);
314 case ValID::ConstantVal: // Fully resolved constant?
315 if (D.ConstantValue->getType() != Ty)
316 ThrowException("Constant expression type different from required type!");
317 return D.ConstantValue;
320 assert(0 && "Unhandled case!");
324 assert(0 && "Unhandled case!");
328 // getVal - This function is identical to getValNonImprovising, except that if a
329 // value is not already defined, it "improvises" by creating a placeholder var
330 // that looks and acts just like the requested variable. When the value is
331 // defined later, all uses of the placeholder variable are replaced with the
334 static Value *getVal(const Type *Ty, const ValID &ID) {
335 if (Ty == Type::LabelTy)
336 ThrowException("Cannot use a basic block here");
338 // See if the value has already been defined.
339 Value *V = getValNonImprovising(Ty, ID);
342 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
343 ThrowException("Invalid use of a composite type!");
345 // If we reached here, we referenced either a symbol that we don't know about
346 // or an id number that hasn't been read yet. We may be referencing something
347 // forward, so just create an entry to be resolved later and get to it...
349 V = new Argument(Ty);
351 // Remember where this forward reference came from. FIXME, shouldn't we try
352 // to recycle these things??
353 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
356 if (inFunctionScope())
357 InsertValue(V, CurFun.LateResolveValues);
359 InsertValue(V, CurModule.LateResolveValues);
363 /// getBBVal - This is used for two purposes:
364 /// * If isDefinition is true, a new basic block with the specified ID is being
366 /// * If isDefinition is true, this is a reference to a basic block, which may
367 /// or may not be a forward reference.
369 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
370 assert(inFunctionScope() && "Can't get basic block at global scope!");
375 default: ThrowException("Illegal label reference " + ID.getName());
376 case ValID::NumberVal: // Is it a numbered definition?
377 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
378 CurFun.NumberedBlocks.resize(ID.Num+1);
379 BB = CurFun.NumberedBlocks[ID.Num];
381 case ValID::NameVal: // Is it a named definition?
383 if (Value *N = CurFun.CurrentFunction->
384 getSymbolTable().lookup(Type::LabelTy, Name))
385 BB = cast<BasicBlock>(N);
389 // See if the block has already been defined.
391 // If this is the definition of the block, make sure the existing value was
392 // just a forward reference. If it was a forward reference, there will be
393 // an entry for it in the PlaceHolderInfo map.
394 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
395 // The existing value was a definition, not a forward reference.
396 ThrowException("Redefinition of label " + ID.getName());
398 ID.destroy(); // Free strdup'd memory.
402 // Otherwise this block has not been seen before.
403 BB = new BasicBlock("", CurFun.CurrentFunction);
404 if (ID.Type == ValID::NameVal) {
405 BB->setName(ID.Name);
407 CurFun.NumberedBlocks[ID.Num] = BB;
410 // If this is not a definition, keep track of it so we can use it as a forward
413 // Remember where this forward reference came from.
414 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
416 // The forward declaration could have been inserted anywhere in the
417 // function: insert it into the correct place now.
418 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
419 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
426 //===----------------------------------------------------------------------===//
427 // Code to handle forward references in instructions
428 //===----------------------------------------------------------------------===//
430 // This code handles the late binding needed with statements that reference
431 // values not defined yet... for example, a forward branch, or the PHI node for
434 // This keeps a table (CurFun.LateResolveValues) of all such forward references
435 // and back patchs after we are done.
438 // ResolveDefinitions - If we could not resolve some defs at parsing
439 // time (forward branches, phi functions for loops, etc...) resolve the
443 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
444 std::map<const Type*,ValueList> *FutureLateResolvers) {
445 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
446 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
447 E = LateResolvers.end(); LRI != E; ++LRI) {
448 ValueList &List = LRI->second;
449 while (!List.empty()) {
450 Value *V = List.back();
453 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
454 CurModule.PlaceHolderInfo.find(V);
455 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
457 ValID &DID = PHI->second.first;
459 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
461 V->replaceAllUsesWith(TheRealValue);
463 CurModule.PlaceHolderInfo.erase(PHI);
464 } else if (FutureLateResolvers) {
465 // Functions have their unresolved items forwarded to the module late
467 InsertValue(V, *FutureLateResolvers);
469 if (DID.Type == ValID::NameVal)
470 ThrowException("Reference to an invalid definition: '" +DID.getName()+
471 "' of type '" + V->getType()->getDescription() + "'",
474 ThrowException("Reference to an invalid definition: #" +
475 itostr(DID.Num) + " of type '" +
476 V->getType()->getDescription() + "'",
482 LateResolvers.clear();
485 // ResolveTypeTo - A brand new type was just declared. This means that (if
486 // name is not null) things referencing Name can be resolved. Otherwise, things
487 // refering to the number can be resolved. Do this now.
489 static void ResolveTypeTo(char *Name, const Type *ToTy) {
491 if (Name) D = ValID::create(Name);
492 else D = ValID::create((int)CurModule.Types.size());
494 std::map<ValID, PATypeHolder>::iterator I =
495 CurModule.LateResolveTypes.find(D);
496 if (I != CurModule.LateResolveTypes.end()) {
497 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
498 CurModule.LateResolveTypes.erase(I);
502 // setValueName - Set the specified value to the name given. The name may be
503 // null potentially, in which case this is a noop. The string passed in is
504 // assumed to be a malloc'd string buffer, and is free'd by this function.
506 static void setValueName(Value *V, char *NameStr) {
508 std::string Name(NameStr); // Copy string
509 free(NameStr); // Free old string
511 if (V->getType() == Type::VoidTy)
512 ThrowException("Can't assign name '" + Name+"' to value with void type!");
514 assert(inFunctionScope() && "Must be in function scope!");
515 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
516 if (ST.lookup(V->getType(), Name))
517 ThrowException("Redefinition of value named '" + Name + "' in the '" +
518 V->getType()->getDescription() + "' type plane!");
525 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
526 /// this is a declaration, otherwise it is a definition.
527 static GlobalVariable *
528 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
529 bool isConstantGlobal, const Type *Ty,
530 Constant *Initializer) {
531 if (isa<FunctionType>(Ty))
532 ThrowException("Cannot declare global vars of function type!");
534 const PointerType *PTy = PointerType::get(Ty);
538 Name = NameStr; // Copy string
539 free(NameStr); // Free old string
542 // See if this global value was forward referenced. If so, recycle the
546 ID = ValID::create((char*)Name.c_str());
548 ID = ValID::create((int)CurModule.Values[PTy].size());
551 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
552 // Move the global to the end of the list, from whereever it was
553 // previously inserted.
554 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
555 CurModule.CurrentModule->getGlobalList().remove(GV);
556 CurModule.CurrentModule->getGlobalList().push_back(GV);
557 GV->setInitializer(Initializer);
558 GV->setLinkage(Linkage);
559 GV->setConstant(isConstantGlobal);
560 InsertValue(GV, CurModule.Values);
564 // If this global has a name, check to see if there is already a definition
565 // of this global in the module. If so, merge as appropriate. Note that
566 // this is really just a hack around problems in the CFE. :(
568 // We are a simple redefinition of a value, check to see if it is defined
569 // the same as the old one.
570 if (GlobalVariable *EGV =
571 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
572 // We are allowed to redefine a global variable in two circumstances:
573 // 1. If at least one of the globals is uninitialized or
574 // 2. If both initializers have the same value.
576 if (!EGV->hasInitializer() || !Initializer ||
577 EGV->getInitializer() == Initializer) {
579 // Make sure the existing global version gets the initializer! Make
580 // sure that it also gets marked const if the new version is.
581 if (Initializer && !EGV->hasInitializer())
582 EGV->setInitializer(Initializer);
583 if (isConstantGlobal)
584 EGV->setConstant(true);
585 EGV->setLinkage(Linkage);
589 ThrowException("Redefinition of global variable named '" + Name +
590 "' in the '" + Ty->getDescription() + "' type plane!");
594 // Otherwise there is no existing GV to use, create one now.
596 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
597 CurModule.CurrentModule);
598 InsertValue(GV, CurModule.Values);
602 // setTypeName - Set the specified type to the name given. The name may be
603 // null potentially, in which case this is a noop. The string passed in is
604 // assumed to be a malloc'd string buffer, and is freed by this function.
606 // This function returns true if the type has already been defined, but is
607 // allowed to be redefined in the specified context. If the name is a new name
608 // for the type plane, it is inserted and false is returned.
609 static bool setTypeName(const Type *T, char *NameStr) {
610 assert(!inFunctionScope() && "Can't give types function-local names!");
611 if (NameStr == 0) return false;
613 std::string Name(NameStr); // Copy string
614 free(NameStr); // Free old string
616 // We don't allow assigning names to void type
617 if (T == Type::VoidTy)
618 ThrowException("Can't assign name '" + Name + "' to the void type!");
620 // Set the type name, checking for conflicts as we do so.
621 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
623 if (AlreadyExists) { // Inserting a name that is already defined???
624 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
625 assert(Existing && "Conflict but no matching type?");
627 // There is only one case where this is allowed: when we are refining an
628 // opaque type. In this case, Existing will be an opaque type.
629 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
630 // We ARE replacing an opaque type!
631 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
635 // Otherwise, this is an attempt to redefine a type. That's okay if
636 // the redefinition is identical to the original. This will be so if
637 // Existing and T point to the same Type object. In this one case we
638 // allow the equivalent redefinition.
639 if (Existing == T) return true; // Yes, it's equal.
641 // Any other kind of (non-equivalent) redefinition is an error.
642 ThrowException("Redefinition of type named '" + Name + "' in the '" +
643 T->getDescription() + "' type plane!");
649 //===----------------------------------------------------------------------===//
650 // Code for handling upreferences in type names...
653 // TypeContains - Returns true if Ty directly contains E in it.
655 static bool TypeContains(const Type *Ty, const Type *E) {
656 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
657 E) != Ty->subtype_end();
662 // NestingLevel - The number of nesting levels that need to be popped before
663 // this type is resolved.
664 unsigned NestingLevel;
666 // LastContainedTy - This is the type at the current binding level for the
667 // type. Every time we reduce the nesting level, this gets updated.
668 const Type *LastContainedTy;
670 // UpRefTy - This is the actual opaque type that the upreference is
674 UpRefRecord(unsigned NL, OpaqueType *URTy)
675 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
679 // UpRefs - A list of the outstanding upreferences that need to be resolved.
680 static std::vector<UpRefRecord> UpRefs;
682 /// HandleUpRefs - Every time we finish a new layer of types, this function is
683 /// called. It loops through the UpRefs vector, which is a list of the
684 /// currently active types. For each type, if the up reference is contained in
685 /// the newly completed type, we decrement the level count. When the level
686 /// count reaches zero, the upreferenced type is the type that is passed in:
687 /// thus we can complete the cycle.
689 static PATypeHolder HandleUpRefs(const Type *ty) {
690 if (!ty->isAbstract()) return ty;
692 UR_OUT("Type '" << Ty->getDescription() <<
693 "' newly formed. Resolving upreferences.\n" <<
694 UpRefs.size() << " upreferences active!\n");
696 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
697 // to zero), we resolve them all together before we resolve them to Ty. At
698 // the end of the loop, if there is anything to resolve to Ty, it will be in
700 OpaqueType *TypeToResolve = 0;
702 for (unsigned i = 0; i != UpRefs.size(); ++i) {
703 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
704 << UpRefs[i].second->getDescription() << ") = "
705 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
706 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
707 // Decrement level of upreference
708 unsigned Level = --UpRefs[i].NestingLevel;
709 UpRefs[i].LastContainedTy = Ty;
710 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
711 if (Level == 0) { // Upreference should be resolved!
712 if (!TypeToResolve) {
713 TypeToResolve = UpRefs[i].UpRefTy;
715 UR_OUT(" * Resolving upreference for "
716 << UpRefs[i].second->getDescription() << "\n";
717 std::string OldName = UpRefs[i].UpRefTy->getDescription());
718 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
719 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
720 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
722 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
723 --i; // Do not skip the next element...
729 UR_OUT(" * Resolving upreference for "
730 << UpRefs[i].second->getDescription() << "\n";
731 std::string OldName = TypeToResolve->getDescription());
732 TypeToResolve->refineAbstractTypeTo(Ty);
739 // common code from the two 'RunVMAsmParser' functions
740 static Module * RunParser(Module * M) {
742 llvmAsmlineno = 1; // Reset the current line number...
743 ObsoleteVarArgs = false;
746 CurModule.CurrentModule = M;
747 yyparse(); // Parse the file, potentially throwing exception
749 Module *Result = ParserResult;
752 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
755 if ((F = Result->getNamedFunction("llvm.va_start"))
756 && F->getFunctionType()->getNumParams() == 0)
757 ObsoleteVarArgs = true;
758 if((F = Result->getNamedFunction("llvm.va_copy"))
759 && F->getFunctionType()->getNumParams() == 1)
760 ObsoleteVarArgs = true;
763 if (ObsoleteVarArgs && NewVarArgs)
764 ThrowException("This file is corrupt: it uses both new and old style varargs");
766 if(ObsoleteVarArgs) {
767 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
768 if (F->arg_size() != 0)
769 ThrowException("Obsolete va_start takes 0 argument!");
773 //bar = alloca typeof(foo)
777 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
778 const Type* ArgTy = F->getFunctionType()->getReturnType();
779 const Type* ArgTyPtr = PointerType::get(ArgTy);
780 Function* NF = Result->getOrInsertFunction("llvm.va_start",
781 RetTy, ArgTyPtr, (Type *)0);
783 while (!F->use_empty()) {
784 CallInst* CI = cast<CallInst>(F->use_back());
785 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
786 new CallInst(NF, bar, "", CI);
787 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
788 CI->replaceAllUsesWith(foo);
789 CI->getParent()->getInstList().erase(CI);
791 Result->getFunctionList().erase(F);
794 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
795 if(F->arg_size() != 1)
796 ThrowException("Obsolete va_end takes 1 argument!");
800 //bar = alloca 1 of typeof(foo)
802 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
803 const Type* ArgTy = F->getFunctionType()->getParamType(0);
804 const Type* ArgTyPtr = PointerType::get(ArgTy);
805 Function* NF = Result->getOrInsertFunction("llvm.va_end",
806 RetTy, ArgTyPtr, (Type *)0);
808 while (!F->use_empty()) {
809 CallInst* CI = cast<CallInst>(F->use_back());
810 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
811 new StoreInst(CI->getOperand(1), bar, CI);
812 new CallInst(NF, bar, "", CI);
813 CI->getParent()->getInstList().erase(CI);
815 Result->getFunctionList().erase(F);
818 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
819 if(F->arg_size() != 1)
820 ThrowException("Obsolete va_copy takes 1 argument!");
823 //a = alloca 1 of typeof(foo)
824 //b = alloca 1 of typeof(foo)
829 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
830 const Type* ArgTy = F->getFunctionType()->getReturnType();
831 const Type* ArgTyPtr = PointerType::get(ArgTy);
832 Function* NF = Result->getOrInsertFunction("llvm.va_copy",
833 RetTy, ArgTyPtr, ArgTyPtr,
836 while (!F->use_empty()) {
837 CallInst* CI = cast<CallInst>(F->use_back());
838 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
839 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
840 new StoreInst(CI->getOperand(1), b, CI);
841 new CallInst(NF, a, b, "", CI);
842 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
843 CI->replaceAllUsesWith(foo);
844 CI->getParent()->getInstList().erase(CI);
846 Result->getFunctionList().erase(F);
854 //===----------------------------------------------------------------------===//
855 // RunVMAsmParser - Define an interface to this parser
856 //===----------------------------------------------------------------------===//
858 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
861 CurFilename = Filename;
862 return RunParser(new Module(CurFilename));
865 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
866 set_scan_string(AsmString);
868 CurFilename = "from_memory";
870 return RunParser(new Module (CurFilename));
879 llvm::Module *ModuleVal;
880 llvm::Function *FunctionVal;
881 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
882 llvm::BasicBlock *BasicBlockVal;
883 llvm::TerminatorInst *TermInstVal;
884 llvm::Instruction *InstVal;
885 llvm::Constant *ConstVal;
887 const llvm::Type *PrimType;
888 llvm::PATypeHolder *TypeVal;
889 llvm::Value *ValueVal;
891 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
892 std::vector<llvm::Value*> *ValueList;
893 std::list<llvm::PATypeHolder> *TypeList;
894 // Represent the RHS of PHI node
895 std::list<std::pair<llvm::Value*,
896 llvm::BasicBlock*> > *PHIList;
897 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
898 std::vector<llvm::Constant*> *ConstVector;
900 llvm::GlobalValue::LinkageTypes Linkage;
908 char *StrVal; // This memory is strdup'd!
909 llvm::ValID ValIDVal; // strdup'd memory maybe!
911 llvm::Instruction::BinaryOps BinaryOpVal;
912 llvm::Instruction::TermOps TermOpVal;
913 llvm::Instruction::MemoryOps MemOpVal;
914 llvm::Instruction::OtherOps OtherOpVal;
915 llvm::Module::Endianness Endianness;
918 %type <ModuleVal> Module FunctionList
919 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
920 %type <BasicBlockVal> BasicBlock InstructionList
921 %type <TermInstVal> BBTerminatorInst
922 %type <InstVal> Inst InstVal MemoryInst
923 %type <ConstVal> ConstVal ConstExpr
924 %type <ConstVector> ConstVector
925 %type <ArgList> ArgList ArgListH
926 %type <ArgVal> ArgVal
927 %type <PHIList> PHIList
928 %type <ValueList> ValueRefList ValueRefListE // For call param lists
929 %type <ValueList> IndexList // For GEP derived indices
930 %type <TypeList> TypeListI ArgTypeListI
931 %type <JumpTable> JumpTable
932 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
933 %type <BoolVal> OptVolatile // 'volatile' or not
934 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
935 %type <Linkage> OptLinkage
936 %type <Endianness> BigOrLittle
938 // ValueRef - Unresolved reference to a definition or BB
939 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
940 %type <ValueVal> ResolvedVal // <type> <valref> pair
941 // Tokens and types for handling constant integer values
943 // ESINT64VAL - A negative number within long long range
944 %token <SInt64Val> ESINT64VAL
946 // EUINT64VAL - A positive number within uns. long long range
947 %token <UInt64Val> EUINT64VAL
948 %type <SInt64Val> EINT64VAL
950 %token <SIntVal> SINTVAL // Signed 32 bit ints...
951 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
952 %type <SIntVal> INTVAL
953 %token <FPVal> FPVAL // Float or Double constant
956 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
957 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
958 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
959 %token <PrimType> FLOAT DOUBLE TYPE LABEL
961 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
962 %type <StrVal> Name OptName OptAssign
963 %type <UIntVal> OptAlign OptCAlign
964 %type <StrVal> OptSection SectionString
966 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
967 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
968 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
969 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
970 %token DEPLIBS CALL TAIL
971 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK
972 %type <UIntVal> OptCallingConv
974 // Basic Block Terminating Operators
975 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
978 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
979 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
980 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
982 // Memory Instructions
983 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
986 %type <OtherOpVal> ShiftOps
987 %token <OtherOpVal> PHI_TOK CAST SELECT SHL SHR VAARG EXTRACTELEMENT
988 %token VAARG_old VANEXT_old //OBSOLETE
994 // Handle constant integer size restriction and conversion...
998 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
999 ThrowException("Value too large for type!");
1004 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
1005 EINT64VAL : EUINT64VAL {
1006 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1007 ThrowException("Value too large for type!");
1011 // Operations that are notably excluded from this list include:
1012 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1014 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
1015 LogicalOps : AND | OR | XOR;
1016 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1018 ShiftOps : SHL | SHR;
1020 // These are some types that allow classification if we only want a particular
1021 // thing... for example, only a signed, unsigned, or integral type.
1022 SIntType : LONG | INT | SHORT | SBYTE;
1023 UIntType : ULONG | UINT | USHORT | UBYTE;
1024 IntType : SIntType | UIntType;
1025 FPType : FLOAT | DOUBLE;
1027 // OptAssign - Value producing statements have an optional assignment component
1028 OptAssign : Name '=' {
1035 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
1036 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
1037 WEAK { $$ = GlobalValue::WeakLinkage; } |
1038 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1039 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1041 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1042 CCC_TOK { $$ = CallingConv::C; } |
1043 FASTCC_TOK { $$ = CallingConv::Fast; } |
1044 COLDCC_TOK { $$ = CallingConv::Cold; } |
1046 if ((unsigned)$2 != $2)
1047 ThrowException("Calling conv too large!");
1051 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1052 // a comma before it.
1053 OptAlign : /*empty*/ { $$ = 0; } |
1056 if ($$ != 0 && !isPowerOf2_32($$))
1057 ThrowException("Alignment must be a power of two!");
1059 OptCAlign : /*empty*/ { $$ = 0; } |
1060 ',' ALIGN EUINT64VAL {
1062 if ($$ != 0 && !isPowerOf2_32($$))
1063 ThrowException("Alignment must be a power of two!");
1067 SectionString : SECTION STRINGCONSTANT {
1068 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1069 if ($2[i] == '"' || $2[i] == '\\')
1070 ThrowException("Invalid character in section name!");
1074 OptSection : /*empty*/ { $$ = 0; } |
1075 SectionString { $$ = $1; };
1077 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1078 // is set to be the global we are processing.
1080 GlobalVarAttributes : /* empty */ {} |
1081 ',' GlobalVarAttribute GlobalVarAttributes {};
1082 GlobalVarAttribute : SectionString {
1083 CurGV->setSection($1);
1086 | ALIGN EUINT64VAL {
1087 if ($2 != 0 && !isPowerOf2_32($2))
1088 ThrowException("Alignment must be a power of two!");
1089 CurGV->setAlignment($2);
1092 //===----------------------------------------------------------------------===//
1093 // Types includes all predefined types... except void, because it can only be
1094 // used in specific contexts (function returning void for example). To have
1095 // access to it, a user must explicitly use TypesV.
1098 // TypesV includes all of 'Types', but it also includes the void type.
1099 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
1100 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1103 if (!UpRefs.empty())
1104 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
1109 // Derived types are added later...
1111 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
1112 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
1114 $$ = new PATypeHolder(OpaqueType::get());
1117 $$ = new PATypeHolder($1);
1119 UpRTypes : SymbolicValueRef { // Named types are also simple types...
1120 $$ = new PATypeHolder(getTypeVal($1));
1123 // Include derived types in the Types production.
1125 UpRTypes : '\\' EUINT64VAL { // Type UpReference
1126 if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
1127 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1128 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1129 $$ = new PATypeHolder(OT);
1130 UR_OUT("New Upreference!\n");
1132 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1133 std::vector<const Type*> Params;
1134 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1135 E = $3->end(); I != E; ++I)
1136 Params.push_back(*I);
1137 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1138 if (isVarArg) Params.pop_back();
1140 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1141 delete $3; // Delete the argument list
1142 delete $1; // Delete the return type handle
1144 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1145 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1148 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1149 const llvm::Type* ElemTy = $4->get();
1150 if ((unsigned)$2 != $2)
1151 ThrowException("Unsigned result not equal to signed result");
1152 if (!ElemTy->isPrimitiveType())
1153 ThrowException("Elemental type of a PackedType must be primitive");
1154 if (!isPowerOf2_32($2))
1155 ThrowException("Vector length should be a power of 2!");
1156 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1159 | '{' TypeListI '}' { // Structure type?
1160 std::vector<const Type*> Elements;
1161 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1162 E = $2->end(); I != E; ++I)
1163 Elements.push_back(*I);
1165 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1168 | '{' '}' { // Empty structure type?
1169 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1171 | UpRTypes '*' { // Pointer type?
1172 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1176 // TypeList - Used for struct declarations and as a basis for function type
1177 // declaration type lists
1179 TypeListI : UpRTypes {
1180 $$ = new std::list<PATypeHolder>();
1181 $$->push_back(*$1); delete $1;
1183 | TypeListI ',' UpRTypes {
1184 ($$=$1)->push_back(*$3); delete $3;
1187 // ArgTypeList - List of types for a function type declaration...
1188 ArgTypeListI : TypeListI
1189 | TypeListI ',' DOTDOTDOT {
1190 ($$=$1)->push_back(Type::VoidTy);
1193 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1196 $$ = new std::list<PATypeHolder>();
1199 // ConstVal - The various declarations that go into the constant pool. This
1200 // production is used ONLY to represent constants that show up AFTER a 'const',
1201 // 'constant' or 'global' token at global scope. Constants that can be inlined
1202 // into other expressions (such as integers and constexprs) are handled by the
1203 // ResolvedVal, ValueRef and ConstValueRef productions.
1205 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1206 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1208 ThrowException("Cannot make array constant with type: '" +
1209 (*$1)->getDescription() + "'!");
1210 const Type *ETy = ATy->getElementType();
1211 int NumElements = ATy->getNumElements();
1213 // Verify that we have the correct size...
1214 if (NumElements != -1 && NumElements != (int)$3->size())
1215 ThrowException("Type mismatch: constant sized array initialized with " +
1216 utostr($3->size()) + " arguments, but has size of " +
1217 itostr(NumElements) + "!");
1219 // Verify all elements are correct type!
1220 for (unsigned i = 0; i < $3->size(); i++) {
1221 if (ETy != (*$3)[i]->getType())
1222 ThrowException("Element #" + utostr(i) + " is not of type '" +
1223 ETy->getDescription() +"' as required!\nIt is of type '"+
1224 (*$3)[i]->getType()->getDescription() + "'.");
1227 $$ = ConstantArray::get(ATy, *$3);
1228 delete $1; delete $3;
1231 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1233 ThrowException("Cannot make array constant with type: '" +
1234 (*$1)->getDescription() + "'!");
1236 int NumElements = ATy->getNumElements();
1237 if (NumElements != -1 && NumElements != 0)
1238 ThrowException("Type mismatch: constant sized array initialized with 0"
1239 " arguments, but has size of " + itostr(NumElements) +"!");
1240 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1243 | Types 'c' STRINGCONSTANT {
1244 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1246 ThrowException("Cannot make array constant with type: '" +
1247 (*$1)->getDescription() + "'!");
1249 int NumElements = ATy->getNumElements();
1250 const Type *ETy = ATy->getElementType();
1251 char *EndStr = UnEscapeLexed($3, true);
1252 if (NumElements != -1 && NumElements != (EndStr-$3))
1253 ThrowException("Can't build string constant of size " +
1254 itostr((int)(EndStr-$3)) +
1255 " when array has size " + itostr(NumElements) + "!");
1256 std::vector<Constant*> Vals;
1257 if (ETy == Type::SByteTy) {
1258 for (char *C = $3; C != EndStr; ++C)
1259 Vals.push_back(ConstantSInt::get(ETy, *C));
1260 } else if (ETy == Type::UByteTy) {
1261 for (char *C = $3; C != EndStr; ++C)
1262 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1265 ThrowException("Cannot build string arrays of non byte sized elements!");
1268 $$ = ConstantArray::get(ATy, Vals);
1271 | Types '<' ConstVector '>' { // Nonempty unsized arr
1272 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1274 ThrowException("Cannot make packed constant with type: '" +
1275 (*$1)->getDescription() + "'!");
1276 const Type *ETy = PTy->getElementType();
1277 int NumElements = PTy->getNumElements();
1279 // Verify that we have the correct size...
1280 if (NumElements != -1 && NumElements != (int)$3->size())
1281 ThrowException("Type mismatch: constant sized packed initialized with " +
1282 utostr($3->size()) + " arguments, but has size of " +
1283 itostr(NumElements) + "!");
1285 // Verify all elements are correct type!
1286 for (unsigned i = 0; i < $3->size(); i++) {
1287 if (ETy != (*$3)[i]->getType())
1288 ThrowException("Element #" + utostr(i) + " is not of type '" +
1289 ETy->getDescription() +"' as required!\nIt is of type '"+
1290 (*$3)[i]->getType()->getDescription() + "'.");
1293 $$ = ConstantPacked::get(PTy, *$3);
1294 delete $1; delete $3;
1296 | Types '{' ConstVector '}' {
1297 const StructType *STy = dyn_cast<StructType>($1->get());
1299 ThrowException("Cannot make struct constant with type: '" +
1300 (*$1)->getDescription() + "'!");
1302 if ($3->size() != STy->getNumContainedTypes())
1303 ThrowException("Illegal number of initializers for structure type!");
1305 // Check to ensure that constants are compatible with the type initializer!
1306 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1307 if ((*$3)[i]->getType() != STy->getElementType(i))
1308 ThrowException("Expected type '" +
1309 STy->getElementType(i)->getDescription() +
1310 "' for element #" + utostr(i) +
1311 " of structure initializer!");
1313 $$ = ConstantStruct::get(STy, *$3);
1314 delete $1; delete $3;
1317 const StructType *STy = dyn_cast<StructType>($1->get());
1319 ThrowException("Cannot make struct constant with type: '" +
1320 (*$1)->getDescription() + "'!");
1322 if (STy->getNumContainedTypes() != 0)
1323 ThrowException("Illegal number of initializers for structure type!");
1325 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1329 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1331 ThrowException("Cannot make null pointer constant with type: '" +
1332 (*$1)->getDescription() + "'!");
1334 $$ = ConstantPointerNull::get(PTy);
1338 $$ = UndefValue::get($1->get());
1341 | Types SymbolicValueRef {
1342 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1344 ThrowException("Global const reference must be a pointer type!");
1346 // ConstExprs can exist in the body of a function, thus creating
1347 // GlobalValues whenever they refer to a variable. Because we are in
1348 // the context of a function, getValNonImprovising will search the functions
1349 // symbol table instead of the module symbol table for the global symbol,
1350 // which throws things all off. To get around this, we just tell
1351 // getValNonImprovising that we are at global scope here.
1353 Function *SavedCurFn = CurFun.CurrentFunction;
1354 CurFun.CurrentFunction = 0;
1356 Value *V = getValNonImprovising(Ty, $2);
1358 CurFun.CurrentFunction = SavedCurFn;
1360 // If this is an initializer for a constant pointer, which is referencing a
1361 // (currently) undefined variable, create a stub now that shall be replaced
1362 // in the future with the right type of variable.
1365 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1366 const PointerType *PT = cast<PointerType>(Ty);
1368 // First check to see if the forward references value is already created!
1369 PerModuleInfo::GlobalRefsType::iterator I =
1370 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1372 if (I != CurModule.GlobalRefs.end()) {
1373 V = I->second; // Placeholder already exists, use it...
1377 if ($2.Type == ValID::NameVal) Name = $2.Name;
1379 // Create the forward referenced global.
1381 if (const FunctionType *FTy =
1382 dyn_cast<FunctionType>(PT->getElementType())) {
1383 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1384 CurModule.CurrentModule);
1386 GV = new GlobalVariable(PT->getElementType(), false,
1387 GlobalValue::ExternalLinkage, 0,
1388 Name, CurModule.CurrentModule);
1391 // Keep track of the fact that we have a forward ref to recycle it
1392 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1397 $$ = cast<GlobalValue>(V);
1398 delete $1; // Free the type handle
1401 if ($1->get() != $2->getType())
1402 ThrowException("Mismatched types for constant expression!");
1406 | Types ZEROINITIALIZER {
1407 const Type *Ty = $1->get();
1408 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1409 ThrowException("Cannot create a null initialized value of this type!");
1410 $$ = Constant::getNullValue(Ty);
1414 ConstVal : SIntType EINT64VAL { // integral constants
1415 if (!ConstantSInt::isValueValidForType($1, $2))
1416 ThrowException("Constant value doesn't fit in type!");
1417 $$ = ConstantSInt::get($1, $2);
1419 | UIntType EUINT64VAL { // integral constants
1420 if (!ConstantUInt::isValueValidForType($1, $2))
1421 ThrowException("Constant value doesn't fit in type!");
1422 $$ = ConstantUInt::get($1, $2);
1424 | BOOL TRUETOK { // Boolean constants
1425 $$ = ConstantBool::True;
1427 | BOOL FALSETOK { // Boolean constants
1428 $$ = ConstantBool::False;
1430 | FPType FPVAL { // Float & Double constants
1431 if (!ConstantFP::isValueValidForType($1, $2))
1432 ThrowException("Floating point constant invalid for type!!");
1433 $$ = ConstantFP::get($1, $2);
1437 ConstExpr: CAST '(' ConstVal TO Types ')' {
1438 if (!$3->getType()->isFirstClassType())
1439 ThrowException("cast constant expression from a non-primitive type: '" +
1440 $3->getType()->getDescription() + "'!");
1441 if (!$5->get()->isFirstClassType())
1442 ThrowException("cast constant expression to a non-primitive type: '" +
1443 $5->get()->getDescription() + "'!");
1444 $$ = ConstantExpr::getCast($3, $5->get());
1447 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1448 if (!isa<PointerType>($3->getType()))
1449 ThrowException("GetElementPtr requires a pointer operand!");
1451 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
1452 // indices to uint struct indices for compatibility.
1453 generic_gep_type_iterator<std::vector<Value*>::iterator>
1454 GTI = gep_type_begin($3->getType(), $4->begin(), $4->end()),
1455 GTE = gep_type_end($3->getType(), $4->begin(), $4->end());
1456 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
1457 if (isa<StructType>(*GTI)) // Only change struct indices
1458 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
1459 if (CUI->getType() == Type::UByteTy)
1460 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
1463 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1465 ThrowException("Index list invalid for constant getelementptr!");
1467 std::vector<Constant*> IdxVec;
1468 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1469 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1470 IdxVec.push_back(C);
1472 ThrowException("Indices to constant getelementptr must be constants!");
1476 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1478 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1479 if ($3->getType() != Type::BoolTy)
1480 ThrowException("Select condition must be of boolean type!");
1481 if ($5->getType() != $7->getType())
1482 ThrowException("Select operand types must match!");
1483 $$ = ConstantExpr::getSelect($3, $5, $7);
1485 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1486 if ($3->getType() != $5->getType())
1487 ThrowException("Binary operator types must match!");
1488 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
1489 // To retain backward compatibility with these early compilers, we emit a
1490 // cast to the appropriate integer type automatically if we are in the
1491 // broken case. See PR424 for more information.
1492 if (!isa<PointerType>($3->getType())) {
1493 $$ = ConstantExpr::get($1, $3, $5);
1495 const Type *IntPtrTy = 0;
1496 switch (CurModule.CurrentModule->getPointerSize()) {
1497 case Module::Pointer32: IntPtrTy = Type::IntTy; break;
1498 case Module::Pointer64: IntPtrTy = Type::LongTy; break;
1499 default: ThrowException("invalid pointer binary constant expr!");
1501 $$ = ConstantExpr::get($1, ConstantExpr::getCast($3, IntPtrTy),
1502 ConstantExpr::getCast($5, IntPtrTy));
1503 $$ = ConstantExpr::getCast($$, $3->getType());
1506 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1507 if ($3->getType() != $5->getType())
1508 ThrowException("Logical operator types must match!");
1509 if (!$3->getType()->isIntegral()) {
1510 if (!isa<PackedType>($3->getType()) ||
1511 !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1512 ThrowException("Logical operator requires integral operands!");
1514 $$ = ConstantExpr::get($1, $3, $5);
1516 | SetCondOps '(' ConstVal ',' ConstVal ')' {
1517 if ($3->getType() != $5->getType())
1518 ThrowException("setcc operand types must match!");
1519 $$ = ConstantExpr::get($1, $3, $5);
1521 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1522 if ($5->getType() != Type::UByteTy)
1523 ThrowException("Shift count for shift constant must be unsigned byte!");
1524 if (!$3->getType()->isInteger())
1525 ThrowException("Shift constant expression requires integer operand!");
1526 $$ = ConstantExpr::get($1, $3, $5);
1528 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1529 if (!isa<PackedType>($3->getType()))
1530 ThrowException("First operand of extractelement must be "
1532 if ($5->getType() != Type::UIntTy)
1533 ThrowException("Second operand of extractelement must be uint!");
1534 $$ = ConstantExpr::getExtractElement($3, $5);
1537 // ConstVector - A list of comma separated constants.
1538 ConstVector : ConstVector ',' ConstVal {
1539 ($$ = $1)->push_back($3);
1542 $$ = new std::vector<Constant*>();
1547 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1548 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1551 //===----------------------------------------------------------------------===//
1552 // Rules to match Modules
1553 //===----------------------------------------------------------------------===//
1555 // Module rule: Capture the result of parsing the whole file into a result
1558 Module : FunctionList {
1559 $$ = ParserResult = $1;
1560 CurModule.ModuleDone();
1563 // FunctionList - A list of functions, preceeded by a constant pool.
1565 FunctionList : FunctionList Function {
1567 CurFun.FunctionDone();
1569 | FunctionList FunctionProto {
1572 | FunctionList IMPLEMENTATION {
1576 $$ = CurModule.CurrentModule;
1577 // Emit an error if there are any unresolved types left.
1578 if (!CurModule.LateResolveTypes.empty()) {
1579 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1580 if (DID.Type == ValID::NameVal)
1581 ThrowException("Reference to an undefined type: '"+DID.getName() + "'");
1583 ThrowException("Reference to an undefined type: #" + itostr(DID.Num));
1587 // ConstPool - Constants with optional names assigned to them.
1588 ConstPool : ConstPool OptAssign TYPE TypesV {
1589 // Eagerly resolve types. This is not an optimization, this is a
1590 // requirement that is due to the fact that we could have this:
1592 // %list = type { %list * }
1593 // %list = type { %list * } ; repeated type decl
1595 // If types are not resolved eagerly, then the two types will not be
1596 // determined to be the same type!
1598 ResolveTypeTo($2, *$4);
1600 if (!setTypeName(*$4, $2) && !$2) {
1601 // If this is a named type that is not a redefinition, add it to the slot
1603 CurModule.Types.push_back(*$4);
1608 | ConstPool FunctionProto { // Function prototypes can be in const pool
1610 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1611 if ($5 == 0) ThrowException("Global value initializer is not a constant!");
1612 CurGV = ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1613 } GlobalVarAttributes {
1616 | ConstPool OptAssign EXTERNAL GlobalType Types {
1617 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage,
1620 } GlobalVarAttributes {
1623 | ConstPool TARGET TargetDefinition {
1625 | ConstPool DEPLIBS '=' LibrariesDefinition {
1627 | /* empty: end of list */ {
1632 BigOrLittle : BIG { $$ = Module::BigEndian; };
1633 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1635 TargetDefinition : ENDIAN '=' BigOrLittle {
1636 CurModule.CurrentModule->setEndianness($3);
1638 | POINTERSIZE '=' EUINT64VAL {
1640 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1642 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1644 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1646 | TRIPLE '=' STRINGCONSTANT {
1647 CurModule.CurrentModule->setTargetTriple($3);
1651 LibrariesDefinition : '[' LibList ']';
1653 LibList : LibList ',' STRINGCONSTANT {
1654 CurModule.CurrentModule->addLibrary($3);
1658 CurModule.CurrentModule->addLibrary($1);
1661 | /* empty: end of list */ {
1665 //===----------------------------------------------------------------------===//
1666 // Rules to match Function Headers
1667 //===----------------------------------------------------------------------===//
1669 Name : VAR_ID | STRINGCONSTANT;
1670 OptName : Name | /*empty*/ { $$ = 0; };
1672 ArgVal : Types OptName {
1673 if (*$1 == Type::VoidTy)
1674 ThrowException("void typed arguments are invalid!");
1675 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1678 ArgListH : ArgListH ',' ArgVal {
1684 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1689 ArgList : ArgListH {
1692 | ArgListH ',' DOTDOTDOT {
1694 $$->push_back(std::pair<PATypeHolder*,
1695 char*>(new PATypeHolder(Type::VoidTy), 0));
1698 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1699 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1705 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')'
1706 OptSection OptAlign {
1708 std::string FunctionName($3);
1709 free($3); // Free strdup'd memory!
1711 if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
1712 ThrowException("LLVM functions cannot return aggregate types!");
1714 std::vector<const Type*> ParamTypeList;
1715 if ($5) { // If there are arguments...
1716 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1717 I != $5->end(); ++I)
1718 ParamTypeList.push_back(I->first->get());
1721 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1722 if (isVarArg) ParamTypeList.pop_back();
1724 const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1725 const PointerType *PFT = PointerType::get(FT);
1729 if (!FunctionName.empty()) {
1730 ID = ValID::create((char*)FunctionName.c_str());
1732 ID = ValID::create((int)CurModule.Values[PFT].size());
1736 // See if this function was forward referenced. If so, recycle the object.
1737 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1738 // Move the function to the end of the list, from whereever it was
1739 // previously inserted.
1740 Fn = cast<Function>(FWRef);
1741 CurModule.CurrentModule->getFunctionList().remove(Fn);
1742 CurModule.CurrentModule->getFunctionList().push_back(Fn);
1743 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
1744 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1745 // If this is the case, either we need to be a forward decl, or it needs
1747 if (!CurFun.isDeclare && !Fn->isExternal())
1748 ThrowException("Redefinition of function '" + FunctionName + "'!");
1750 // Make sure to strip off any argument names so we can't get conflicts.
1751 if (Fn->isExternal())
1752 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
1756 } else { // Not already defined?
1757 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1758 CurModule.CurrentModule);
1759 InsertValue(Fn, CurModule.Values);
1762 CurFun.FunctionStart(Fn);
1763 Fn->setCallingConv($1);
1764 Fn->setAlignment($8);
1770 // Add all of the arguments we parsed to the function...
1771 if ($5) { // Is null if empty...
1772 if (isVarArg) { // Nuke the last entry
1773 assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
1774 "Not a varargs marker!");
1775 delete $5->back().first;
1776 $5->pop_back(); // Delete the last entry
1778 Function::arg_iterator ArgIt = Fn->arg_begin();
1779 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1780 I != $5->end(); ++I, ++ArgIt) {
1781 delete I->first; // Delete the typeholder...
1783 setValueName(ArgIt, I->second); // Insert arg into symtab...
1787 delete $5; // We're now done with the argument list
1791 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1793 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1794 $$ = CurFun.CurrentFunction;
1796 // Make sure that we keep track of the linkage type even if there was a
1797 // previous "declare".
1801 END : ENDTOK | '}'; // Allow end of '}' to end a function
1803 Function : BasicBlockList END {
1807 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1808 $$ = CurFun.CurrentFunction;
1809 CurFun.FunctionDone();
1812 //===----------------------------------------------------------------------===//
1813 // Rules to match Basic Blocks
1814 //===----------------------------------------------------------------------===//
1816 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1817 $$ = ValID::create($1);
1820 $$ = ValID::create($1);
1822 | FPVAL { // Perhaps it's an FP constant?
1823 $$ = ValID::create($1);
1826 $$ = ValID::create(ConstantBool::True);
1829 $$ = ValID::create(ConstantBool::False);
1832 $$ = ValID::createNull();
1835 $$ = ValID::createUndef();
1837 | ZEROINITIALIZER { // A vector zero constant.
1838 $$ = ValID::createZeroInit();
1840 | '<' ConstVector '>' { // Nonempty unsized packed vector
1841 const Type *ETy = (*$2)[0]->getType();
1842 int NumElements = $2->size();
1844 PackedType* pt = PackedType::get(ETy, NumElements);
1845 PATypeHolder* PTy = new PATypeHolder(
1853 // Verify all elements are correct type!
1854 for (unsigned i = 0; i < $2->size(); i++) {
1855 if (ETy != (*$2)[i]->getType())
1856 ThrowException("Element #" + utostr(i) + " is not of type '" +
1857 ETy->getDescription() +"' as required!\nIt is of type '" +
1858 (*$2)[i]->getType()->getDescription() + "'.");
1861 $$ = ValID::create(ConstantPacked::get(pt, *$2));
1862 delete PTy; delete $2;
1865 $$ = ValID::create($1);
1868 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1871 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1872 $$ = ValID::create($1);
1874 | Name { // Is it a named reference...?
1875 $$ = ValID::create($1);
1878 // ValueRef - A reference to a definition... either constant or symbolic
1879 ValueRef : SymbolicValueRef | ConstValueRef;
1882 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1883 // type immediately preceeds the value reference, and allows complex constant
1884 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1885 ResolvedVal : Types ValueRef {
1886 $$ = getVal(*$1, $2); delete $1;
1889 BasicBlockList : BasicBlockList BasicBlock {
1892 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1897 // Basic blocks are terminated by branching instructions:
1898 // br, br/cc, switch, ret
1900 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1901 setValueName($3, $2);
1904 $1->getInstList().push_back($3);
1909 InstructionList : InstructionList Inst {
1910 $1->getInstList().push_back($2);
1914 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
1916 // Make sure to move the basic block to the correct location in the
1917 // function, instead of leaving it inserted wherever it was first
1919 Function::BasicBlockListType &BBL =
1920 CurFun.CurrentFunction->getBasicBlockList();
1921 BBL.splice(BBL.end(), BBL, $$);
1924 $$ = CurBB = getBBVal(ValID::create($1), true);
1926 // Make sure to move the basic block to the correct location in the
1927 // function, instead of leaving it inserted wherever it was first
1929 Function::BasicBlockListType &BBL =
1930 CurFun.CurrentFunction->getBasicBlockList();
1931 BBL.splice(BBL.end(), BBL, $$);
1934 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1935 $$ = new ReturnInst($2);
1937 | RET VOID { // Return with no result...
1938 $$ = new ReturnInst();
1940 | BR LABEL ValueRef { // Unconditional Branch...
1941 $$ = new BranchInst(getBBVal($3));
1942 } // Conditional Branch...
1943 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1944 $$ = new BranchInst(getBBVal($6), getBBVal($9), getVal(Type::BoolTy, $3));
1946 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1947 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), $8->size());
1950 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1952 for (; I != E; ++I) {
1953 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
1954 S->addCase(CI, I->second);
1956 ThrowException("Switch case is constant, but not a simple integer!");
1960 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1961 SwitchInst *S = new SwitchInst(getVal($2, $3), getBBVal($6), 0);
1964 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
1965 TO LABEL ValueRef UNWIND LABEL ValueRef {
1966 const PointerType *PFTy;
1967 const FunctionType *Ty;
1969 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
1970 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1971 // Pull out the types of all of the arguments...
1972 std::vector<const Type*> ParamTypes;
1974 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
1976 ParamTypes.push_back((*I)->getType());
1979 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1980 if (isVarArg) ParamTypes.pop_back();
1982 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
1983 PFTy = PointerType::get(Ty);
1986 Value *V = getVal(PFTy, $4); // Get the function we're calling...
1988 BasicBlock *Normal = getBBVal($10);
1989 BasicBlock *Except = getBBVal($13);
1991 // Create the call node...
1992 if (!$6) { // Has no arguments?
1993 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1994 } else { // Has arguments?
1995 // Loop through FunctionType's arguments and ensure they are specified
1998 FunctionType::param_iterator I = Ty->param_begin();
1999 FunctionType::param_iterator E = Ty->param_end();
2000 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2002 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2003 if ((*ArgI)->getType() != *I)
2004 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2005 (*I)->getDescription() + "'!");
2007 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2008 ThrowException("Invalid number of parameters detected!");
2010 $$ = new InvokeInst(V, Normal, Except, *$6);
2012 cast<InvokeInst>($$)->setCallingConv($2);
2018 $$ = new UnwindInst();
2021 $$ = new UnreachableInst();
2026 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2028 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2030 ThrowException("May only switch on a constant pool value!");
2032 $$->push_back(std::make_pair(V, getBBVal($6)));
2034 | IntType ConstValueRef ',' LABEL ValueRef {
2035 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2036 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2039 ThrowException("May only switch on a constant pool value!");
2041 $$->push_back(std::make_pair(V, getBBVal($5)));
2044 Inst : OptAssign InstVal {
2045 // Is this definition named?? if so, assign the name...
2046 setValueName($2, $1);
2051 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2052 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2053 $$->push_back(std::make_pair(getVal(*$1, $3), getBBVal($5)));
2056 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2058 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
2063 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
2064 $$ = new std::vector<Value*>();
2067 | ValueRefList ',' ResolvedVal {
2072 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2073 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
2075 OptTailCall : TAIL CALL {
2084 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2085 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2086 !isa<PackedType>((*$2).get()))
2088 "Arithmetic operator requires integer, FP, or packed operands!");
2089 if (isa<PackedType>((*$2).get()) && $1 == Instruction::Rem)
2090 ThrowException("Rem not supported on packed types!");
2091 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2093 ThrowException("binary operator returned null!");
2096 | LogicalOps Types ValueRef ',' ValueRef {
2097 if (!(*$2)->isIntegral()) {
2098 if (!isa<PackedType>($2->get()) ||
2099 !cast<PackedType>($2->get())->getElementType()->isIntegral())
2100 ThrowException("Logical operator requires integral operands!");
2102 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
2104 ThrowException("binary operator returned null!");
2107 | SetCondOps Types ValueRef ',' ValueRef {
2108 if(isa<PackedType>((*$2).get())) {
2110 "PackedTypes currently not supported in setcc instructions!");
2112 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
2114 ThrowException("binary operator returned null!");
2118 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
2119 << " Replacing with 'xor'.\n";
2121 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2123 ThrowException("Expected integral type for not instruction!");
2125 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2127 ThrowException("Could not create a xor instruction!");
2129 | ShiftOps ResolvedVal ',' ResolvedVal {
2130 if ($4->getType() != Type::UByteTy)
2131 ThrowException("Shift amount must be ubyte!");
2132 if (!$2->getType()->isInteger())
2133 ThrowException("Shift constant expression requires integer operand!");
2134 $$ = new ShiftInst($1, $2, $4);
2136 | CAST ResolvedVal TO Types {
2137 if (!$4->get()->isFirstClassType())
2138 ThrowException("cast instruction to a non-primitive type: '" +
2139 $4->get()->getDescription() + "'!");
2140 $$ = new CastInst($2, *$4);
2143 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2144 if ($2->getType() != Type::BoolTy)
2145 ThrowException("select condition must be boolean!");
2146 if ($4->getType() != $6->getType())
2147 ThrowException("select value types should match!");
2148 $$ = new SelectInst($2, $4, $6);
2150 | VAARG ResolvedVal ',' Types {
2152 $$ = new VAArgInst($2, *$4);
2155 | VAARG_old ResolvedVal ',' Types {
2156 ObsoleteVarArgs = true;
2157 const Type* ArgTy = $2->getType();
2158 Function* NF = CurModule.CurrentModule->
2159 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2162 //foo = alloca 1 of t
2166 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
2167 CurBB->getInstList().push_back(foo);
2168 CallInst* bar = new CallInst(NF, $2);
2169 CurBB->getInstList().push_back(bar);
2170 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2171 $$ = new VAArgInst(foo, *$4);
2174 | VANEXT_old ResolvedVal ',' Types {
2175 ObsoleteVarArgs = true;
2176 const Type* ArgTy = $2->getType();
2177 Function* NF = CurModule.CurrentModule->
2178 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0);
2180 //b = vanext a, t ->
2181 //foo = alloca 1 of t
2184 //tmp = vaarg foo, t
2186 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
2187 CurBB->getInstList().push_back(foo);
2188 CallInst* bar = new CallInst(NF, $2);
2189 CurBB->getInstList().push_back(bar);
2190 CurBB->getInstList().push_back(new StoreInst(bar, foo));
2191 Instruction* tmp = new VAArgInst(foo, *$4);
2192 CurBB->getInstList().push_back(tmp);
2193 $$ = new LoadInst(foo);
2196 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2197 if (!isa<PackedType>($2->getType()))
2198 ThrowException("First operand of extractelement must be a "
2199 "packed type val!");
2200 if ($4->getType() != Type::UIntTy)
2201 ThrowException("Second operand of extractelement must be a uint!");
2202 $$ = new ExtractElementInst($2, $4);
2205 const Type *Ty = $2->front().first->getType();
2206 if (!Ty->isFirstClassType())
2207 ThrowException("PHI node operands must be of first class type!");
2208 $$ = new PHINode(Ty);
2209 ((PHINode*)$$)->reserveOperandSpace($2->size());
2210 while ($2->begin() != $2->end()) {
2211 if ($2->front().first->getType() != Ty)
2212 ThrowException("All elements of a PHI node must be of the same type!");
2213 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2216 delete $2; // Free the list...
2218 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
2219 const PointerType *PFTy;
2220 const FunctionType *Ty;
2222 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2223 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2224 // Pull out the types of all of the arguments...
2225 std::vector<const Type*> ParamTypes;
2227 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2229 ParamTypes.push_back((*I)->getType());
2232 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2233 if (isVarArg) ParamTypes.pop_back();
2235 if (!(*$3)->isFirstClassType() && *$3 != Type::VoidTy)
2236 ThrowException("LLVM functions cannot return aggregate types!");
2238 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2239 PFTy = PointerType::get(Ty);
2242 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2244 // Create the call node...
2245 if (!$6) { // Has no arguments?
2246 // Make sure no arguments is a good thing!
2247 if (Ty->getNumParams() != 0)
2248 ThrowException("No arguments passed to a function that "
2249 "expects arguments!");
2251 $$ = new CallInst(V, std::vector<Value*>());
2252 } else { // Has arguments?
2253 // Loop through FunctionType's arguments and ensure they are specified
2256 FunctionType::param_iterator I = Ty->param_begin();
2257 FunctionType::param_iterator E = Ty->param_end();
2258 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2260 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2261 if ((*ArgI)->getType() != *I)
2262 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2263 (*I)->getDescription() + "'!");
2265 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2266 ThrowException("Invalid number of parameters detected!");
2268 $$ = new CallInst(V, *$6);
2270 cast<CallInst>($$)->setTailCall($1);
2271 cast<CallInst>($$)->setCallingConv($2);
2280 // IndexList - List of indices for GEP based instructions...
2281 IndexList : ',' ValueRefList {
2284 $$ = new std::vector<Value*>();
2287 OptVolatile : VOLATILE {
2296 MemoryInst : MALLOC Types OptCAlign {
2297 $$ = new MallocInst(*$2, 0, $3);
2300 | MALLOC Types ',' UINT ValueRef OptCAlign {
2301 $$ = new MallocInst(*$2, getVal($4, $5), $6);
2304 | ALLOCA Types OptCAlign {
2305 $$ = new AllocaInst(*$2, 0, $3);
2308 | ALLOCA Types ',' UINT ValueRef OptCAlign {
2309 $$ = new AllocaInst(*$2, getVal($4, $5), $6);
2312 | FREE ResolvedVal {
2313 if (!isa<PointerType>($2->getType()))
2314 ThrowException("Trying to free nonpointer type " +
2315 $2->getType()->getDescription() + "!");
2316 $$ = new FreeInst($2);
2319 | OptVolatile LOAD Types ValueRef {
2320 if (!isa<PointerType>($3->get()))
2321 ThrowException("Can't load from nonpointer type: " +
2322 (*$3)->getDescription());
2323 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2324 ThrowException("Can't load from pointer of non-first-class type: " +
2325 (*$3)->getDescription());
2326 $$ = new LoadInst(getVal(*$3, $4), "", $1);
2329 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2330 const PointerType *PT = dyn_cast<PointerType>($5->get());
2332 ThrowException("Can't store to a nonpointer type: " +
2333 (*$5)->getDescription());
2334 const Type *ElTy = PT->getElementType();
2335 if (ElTy != $3->getType())
2336 ThrowException("Can't store '" + $3->getType()->getDescription() +
2337 "' into space of type '" + ElTy->getDescription() + "'!");
2339 $$ = new StoreInst($3, getVal(*$5, $6), $1);
2342 | GETELEMENTPTR Types ValueRef IndexList {
2343 if (!isa<PointerType>($2->get()))
2344 ThrowException("getelementptr insn requires pointer operand!");
2346 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte struct
2347 // indices to uint struct indices for compatibility.
2348 generic_gep_type_iterator<std::vector<Value*>::iterator>
2349 GTI = gep_type_begin($2->get(), $4->begin(), $4->end()),
2350 GTE = gep_type_end($2->get(), $4->begin(), $4->end());
2351 for (unsigned i = 0, e = $4->size(); i != e && GTI != GTE; ++i, ++GTI)
2352 if (isa<StructType>(*GTI)) // Only change struct indices
2353 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>((*$4)[i]))
2354 if (CUI->getType() == Type::UByteTy)
2355 (*$4)[i] = ConstantExpr::getCast(CUI, Type::UIntTy);
2357 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2358 ThrowException("Invalid getelementptr indices for type '" +
2359 (*$2)->getDescription()+ "'!");
2360 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
2361 delete $2; delete $4;
2366 int yyerror(const char *ErrorMsg) {
2368 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2369 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2370 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2371 if (yychar == YYEMPTY || yychar == 0)
2372 errMsg += "end-of-file.";
2374 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2375 ThrowException(errMsg);