1 //===-- UpgradeParser.y - Upgrade parser for llvm assmbly -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM 1.9 assembly language.
12 //===----------------------------------------------------------------------===//
15 #include "UpgradeInternals.h"
21 #define YYERROR_VERBOSE 1
22 #define YYINCLUDED_STDLIB_H
25 int yylex(); // declaration" of xxx warnings.
29 static std::string CurFilename;
30 static std::ostream *O = 0;
31 std::istream* LexInput = 0;
32 unsigned SizeOfPointer = 32;
35 // This bool controls whether attributes are ever added to function declarations
36 // definitions and calls.
37 static bool AddAttributes = false;
39 static void warning(const std::string& msg);
41 void UpgradeAssembly(const std::string &infile, std::istream& in,
42 std::ostream &out, bool debug, bool addAttrs)
48 AddAttributes = addAttrs;
52 std::cerr << "llvm-upgrade: parse failed.\n";
53 out << "llvm-upgrade: parse failed.\n";
58 namespace { // Anonymous namespace to keep our implementation local
61 /// This type is used to keep track of the signedness of values. Instead
62 /// of creating llvm::Value directly, the parser will create Value which
63 /// associates a Value* with a Signedness indication.
68 bool isConstant() const { return constant; }
69 ~Value() { delete val; }
73 /// This type is used to keep track of the signedness of the obsolete
74 /// integer types. Instead of creating an llvm::Type directly, the Lexer will
75 /// create instances of Type which retains the signedness indication so
76 /// it can be used by the parser for upgrade decisions.
77 /// For example if "uint" is encountered then the "first" field will be set
78 /// to "int32" and the "second" field will be set to "isUnsigned". If the
79 /// type is not obsolete then "second" will be set to "isSignless".
82 static const Type* get(const std::string &newType, TypeIDs oldType);
83 static const Type* get(const std::string& newType, TypeIDs oldType,
84 const Type* eTy, const Type* rTy);
86 static const Type* get(const std::string& newType, TypeIDs oldType,
87 const Type *eTy, uint64_t elems);
89 static const Type* get(const std::string& newType, TypeIDs oldType,
92 static const Type* get(const std::string& newType, const Type* resTy,
95 const Type* resolve() const;
96 bool operator<(const Type& that) const;
98 bool sameNewTyAs(const Type* that) const {
99 return this->newTy == that->newTy;
102 bool sameOldTyAs(const Type* that) const;
104 TypeIDs getElementTy() const {
106 return elemTy->oldTy;
111 unsigned getUpRefNum() const {
112 assert(oldTy == UpRefTy && "Can't getUpRefNum on non upreference");
113 return atoi(&((getNewTy().c_str())[1])); // skip the slash
116 typedef std::vector<const Type*> UpRefStack;
117 void getSignedness(unsigned &sNum, unsigned &uNum, UpRefStack& stk) const;
118 std::string makeUniqueName(const std::string& BaseName) const;
120 const std::string& getNewTy() const { return newTy; }
121 const Type* getResultType() const { return resultTy; }
122 const Type* getElementType() const { return elemTy; }
124 const Type* getPointerType() const {
125 return get(newTy + "*", PointerTy, this, (Type*)0);
128 bool isUnresolved() const { return oldTy == UnresolvedTy; }
129 bool isUpReference() const { return oldTy == UpRefTy; }
130 bool isVoid() const { return oldTy == VoidTy; }
131 bool isBool() const { return oldTy == BoolTy; }
132 bool isSigned() const {
133 return oldTy == SByteTy || oldTy == ShortTy ||
134 oldTy == IntTy || oldTy == LongTy;
137 bool isUnsigned() const {
138 return oldTy == UByteTy || oldTy == UShortTy ||
139 oldTy == UIntTy || oldTy == ULongTy;
141 bool isSignless() const { return !isSigned() && !isUnsigned(); }
142 bool isInteger() const { return isSigned() || isUnsigned(); }
143 bool isIntegral() const { return oldTy == BoolTy || isInteger(); }
144 bool isFloatingPoint() const { return oldTy == DoubleTy || oldTy == FloatTy; }
145 bool isPacked() const { return oldTy == PackedTy; }
146 bool isPointer() const { return oldTy == PointerTy; }
147 bool isStruct() const { return oldTy == StructTy || oldTy == PackedStructTy; }
148 bool isArray() const { return oldTy == ArrayTy; }
149 bool isOther() const {
150 return !isPacked() && !isPointer() && !isFloatingPoint() && !isIntegral(); }
151 bool isFunction() const { return oldTy == FunctionTy; }
152 bool isComposite() const {
153 return isStruct() || isPointer() || isArray() || isPacked();
156 bool isAttributeCandidate() const {
157 return isIntegral() && getBitWidth() < 32;
160 bool isUnresolvedDeep() const;
162 unsigned getBitWidth() const;
164 const Type* getIndexedType(const Value* V) const;
166 unsigned getNumStructElements() const {
167 return (elements ? elements->size() : 0);
170 const Type* getElement(unsigned idx) const {
172 if (idx < elements->size())
173 return (*elements)[idx];
179 : newTy(), oldTy(UnresolvedTy), elemTy(0), resultTy(0), elements(0),
183 Type(const Type& that); // do not implement
184 Type& operator=(const Type& that); // do not implement
186 ~Type() { delete elements; }
190 bool operator()(const Type* X, const Type* Y) const {
191 assert(X && "Can't compare null pointer");
192 assert(Y && "Can't compare null pointer");
197 typedef std::set<const Type*, ltfunctor> TypeRegMap;
199 static const Type* add_new_type(Type* existing);
207 static TypeRegMap registry;
209 typedef std::vector<const Type*> TypeVector;
210 typedef std::map<std::string,const Type*> TypeMap;
211 typedef std::map<const Type*,std::string> TypePlaneMap;
212 typedef std::map<std::string,TypePlaneMap> GlobalsTypeMap;
213 static TypeVector EnumeratedTypes;
214 static TypeMap NamedTypes;
215 static GlobalsTypeMap Globals;
218 Type::TypeRegMap Type::registry;
219 Type::TypeVector Type::EnumeratedTypes;
220 Type::TypeMap Type::NamedTypes;
221 Type::GlobalsTypeMap Type::Globals;
223 const Type* Type::get(const std::string &newType, TypeIDs oldType) {
224 Type* Ty = new Type();
227 return add_new_type(Ty);
230 const Type* Type::get(const std::string& newType, TypeIDs oldType,
231 const Type* eTy, const Type* rTy) {
232 Type* Ty= new Type();
235 Ty->elemTy = const_cast<Type*>(eTy);
236 Ty->resultTy = const_cast<Type*>(rTy);
237 return add_new_type(Ty);
240 const Type* Type::get(const std::string& newType, TypeIDs oldType,
241 const Type *eTy, uint64_t elems) {
242 Type* Ty = new Type();
245 Ty->elemTy = const_cast<Type*>(eTy);
247 return add_new_type(Ty);
250 const Type* Type::get(const std::string& newType, TypeIDs oldType,
252 Type* Ty = new Type();
256 return add_new_type(Ty);
259 const Type* Type::get(const std::string& newType, const Type* resTy,
261 Type* Ty = new Type();
263 Ty->oldTy = FunctionTy;
264 Ty->resultTy = const_cast<Type*>(resTy);
266 return add_new_type(Ty);
269 const Type* Type::resolve() const {
270 if (isUnresolved()) {
271 if (getNewTy()[0] == '%' && isdigit(newTy[1])) {
272 unsigned ref = atoi(&((newTy.c_str())[1])); // skip the %
273 if (ref < EnumeratedTypes.size()) {
274 return EnumeratedTypes[ref];
276 std::string msg("Can't resolve numbered type: ");
278 yyerror(msg.c_str());
281 Type::TypeMap::iterator I = NamedTypes.find(newTy);
282 if (I != NamedTypes.end()) {
285 std::string msg("Cannot resolve type: ");
287 yyerror(msg.c_str());
291 // otherwise its already resolved.
295 bool Type::operator<(const Type& that) const {
298 if (oldTy != that.oldTy)
299 return oldTy < that.oldTy;
302 unsigned thisUp = this->getUpRefNum();
303 unsigned thatUp = that.getUpRefNum();
304 return thisUp < thatUp;
308 if (this->nelems != that.nelems)
309 return nelems < that.nelems;
311 const Type* thisTy = this->elemTy;
312 const Type* thatTy = that.elemTy;
313 return *thisTy < *thatTy;
316 const Type* thisTy = this->resultTy;
317 const Type* thatTy = that.resultTy;
318 if (!thisTy->sameOldTyAs(thatTy))
319 return *thisTy < *thatTy;
323 case PackedStructTy: {
324 if (elements->size() != that.elements->size())
325 return elements->size() < that.elements->size();
326 for (unsigned i = 0; i < elements->size(); i++) {
327 const Type* thisTy = (*this->elements)[i];
328 const Type* thatTy = (*that.elements)[i];
329 if (!thisTy->sameOldTyAs(thatTy))
330 return *thisTy < *thatTy;
335 return this->newTy < that.newTy;
342 bool Type::sameOldTyAs(const Type* that) const {
347 if (oldTy != that->oldTy)
352 if (nelems != that->nelems)
356 const Type* thisTy = this->elemTy;
357 const Type* thatTy = that->elemTy;
358 return thisTy->sameOldTyAs(thatTy);
361 const Type* thisTy = this->resultTy;
362 const Type* thatTy = that->resultTy;
363 if (!thisTy->sameOldTyAs(thatTy))
368 case PackedStructTy: {
369 if (elements->size() != that->elements->size())
371 for (unsigned i = 0; i < elements->size(); i++) {
372 const Type* thisTy = (*this->elements)[i];
373 const Type* thatTy = (*that->elements)[i];
374 if (!thisTy->sameOldTyAs(thatTy))
380 return this->newTy == that->newTy;
382 return true; // for all others oldTy == that->oldTy is sufficient
387 bool Type::isUnresolvedDeep() const {
394 return elemTy->isUnresolvedDeep();
397 for (unsigned i = 0; i < elements->size(); i++)
398 if ((*elements)[i]->isUnresolvedDeep())
406 unsigned Type::getBitWidth() const {
410 case VoidTy : return 0;
411 case BoolTy : return 1;
412 case SByteTy: case UByteTy : return 8;
413 case ShortTy: case UShortTy : return 16;
414 case IntTy: case UIntTy: case FloatTy: return 32;
415 case LongTy: case ULongTy: case DoubleTy : return 64;
416 case PointerTy: return SizeOfPointer; // global var
419 return nelems * elemTy->getBitWidth();
421 case PackedStructTy: {
423 for (unsigned i = 0; i < elements->size(); i++) {
424 size += (*elements)[i]->getBitWidth();
431 const Type* Type::getIndexedType(const Value* V) const {
433 if (V->isConstant() && V->type->isInteger()) {
434 size_t pos = V->val->find(' ') + 1;
435 if (pos < V->val->size()) {
436 uint64_t idx = atoi(V->val->substr(pos).c_str());
437 return (*elements)[idx];
439 yyerror("Invalid value for constant integer");
443 yyerror("Structure requires constant index");
447 if (isArray() || isPacked() || isPointer())
449 yyerror("Invalid type for getIndexedType");
453 void Type::getSignedness(unsigned &sNum, unsigned &uNum,
454 UpRefStack& stack) const {
457 case OpaqueTy: case LabelTy: case VoidTy: case BoolTy:
458 case FloatTy : case DoubleTy: case UpRefTy:
460 case SByteTy: case ShortTy: case LongTy: case IntTy:
463 case UByteTy: case UShortTy: case UIntTy: case ULongTy:
469 stack.push_back(this);
470 elemTy->getSignedness(sNum, uNum, stack);
473 case PackedStructTy: {
474 stack.push_back(this);
475 for (unsigned i = 0; i < elements->size(); i++) {
476 (*elements)[i]->getSignedness(sNum, uNum, stack);
481 const Type* Ty = this->resolve();
482 // Let's not recurse.
483 UpRefStack::const_iterator I = stack.begin(), E = stack.end();
484 for ( ; I != E && *I != Ty; ++I)
487 Ty->getSignedness(sNum, uNum, stack);
493 std::string AddSuffix(const std::string& Name, const std::string& Suffix) {
494 if (Name[Name.size()-1] == '"') {
495 std::string Result = Name;
496 Result.insert(Result.size()-1, Suffix);
499 return Name + Suffix;
502 std::string Type::makeUniqueName(const std::string& BaseName) const {
503 if (BaseName == "\"alloca point\"")
508 case OpaqueTy: case LabelTy: case VoidTy: case BoolTy: case UpRefTy:
509 case FloatTy : case DoubleTy: case UnresolvedTy:
511 case SByteTy: case ShortTy: case LongTy: case IntTy:
512 return AddSuffix(BaseName, ".s");
513 case UByteTy: case UShortTy: case UIntTy: case ULongTy:
514 return AddSuffix(BaseName, ".u");
517 unsigned uNum = 0, sNum = 0;
523 Type::UpRefStack stack;
524 elemTy->resolve()->getSignedness(sNum, uNum, stack);
528 case PackedStructTy: {
529 for (unsigned i = 0; i < elements->size(); i++) {
530 Type::UpRefStack stack;
531 (*elements)[i]->resolve()->getSignedness(sNum, uNum, stack);
536 assert(0 && "Invalid Type");
540 if (sNum == 0 && uNum == 0)
544 default: Suffix += ".nada"; break;
545 case PointerTy: Suffix += ".pntr"; break;
546 case PackedTy: Suffix += ".pckd"; break;
547 case ArrayTy: Suffix += ".arry"; break;
548 case StructTy: Suffix += ".strc"; break;
549 case PackedStructTy: Suffix += ".pstr"; break;
552 Suffix += ".s" + llvm::utostr(sNum);
553 Suffix += ".u" + llvm::utostr(uNum);
554 return AddSuffix(BaseName, Suffix);
557 Type& Type::operator=(const Type& that) {
559 nelems = that.nelems;
561 elemTy = that.elemTy;
562 resultTy = that.resultTy;
564 elements = new TypeList(that.elements->size());
565 *elements = *that.elements;
572 const Type* Type::add_new_type(Type* newTy) {
573 TypeRegMap::iterator I = registry.find(newTy);
574 if (I != registry.end()) {
578 registry.insert(newTy);
585 /// This type is used to keep track of the signedness of constants.
589 ~Constant() { delete cnst; }
592 /// This variable provides a counter for unique names. It is used in various
593 /// productions to ensure a unique name is generated.
594 static uint64_t UniqueNameCounter = 1;
596 // This is set when a DECLARE keyword is recognized so that subsequent parsing
597 // of a function prototype can know if its a declaration or definition.
598 static bool isDeclare = false;
600 // This bool is used to communicate between the InstVal and Inst rules about
601 // whether or not a cast should be deleted. When the flag is set, InstVal has
602 // determined that the cast is a candidate. However, it can only be deleted if
603 // the value being casted is the same value name as the instruction. The Inst
604 // rule makes that comparison if the flag is set and comments out the
605 // instruction if they match.
606 static bool deleteUselessCastFlag = false;
607 static std::string* deleteUselessCastName = 0;
611 const char* getCastOpcode(std::string& Source, const Type* SrcTy,
613 unsigned SrcBits = SrcTy->getBitWidth();
614 unsigned DstBits = DstTy->getBitWidth();
615 const char* opcode = "bitcast";
616 // Run through the possibilities ...
617 if (DstTy->isIntegral()) { // Casting to integral
618 if (SrcTy->isIntegral()) { // Casting from integral
619 if (DstBits < SrcBits)
621 else if (DstBits > SrcBits) { // its an extension
622 if (SrcTy->isSigned())
623 opcode ="sext"; // signed -> SEXT
625 opcode = "zext"; // unsigned -> ZEXT
627 opcode = "bitcast"; // Same size, No-op cast
629 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
630 if (DstTy->isSigned())
631 opcode = "fptosi"; // FP -> sint
633 opcode = "fptoui"; // FP -> uint
634 } else if (SrcTy->isPacked()) {
635 assert(DstBits == SrcTy->getBitWidth() &&
636 "Casting packed to integer of different width");
637 opcode = "bitcast"; // same size, no-op cast
639 assert(SrcTy->isPointer() &&
640 "Casting from a value that is not first-class type");
641 opcode = "ptrtoint"; // ptr -> int
643 } else if (DstTy->isFloatingPoint()) { // Casting to floating pt
644 if (SrcTy->isIntegral()) { // Casting from integral
645 if (SrcTy->isSigned())
646 opcode = "sitofp"; // sint -> FP
648 opcode = "uitofp"; // uint -> FP
649 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
650 if (DstBits < SrcBits) {
651 opcode = "fptrunc"; // FP -> smaller FP
652 } else if (DstBits > SrcBits) {
653 opcode = "fpext"; // FP -> larger FP
655 opcode ="bitcast"; // same size, no-op cast
657 } else if (SrcTy->isPacked()) {
658 assert(DstBits == SrcTy->getBitWidth() &&
659 "Casting packed to floating point of different width");
660 opcode = "bitcast"; // same size, no-op cast
662 assert(0 && "Casting pointer or non-first class to float");
664 } else if (DstTy->isPacked()) {
665 if (SrcTy->isPacked()) {
666 assert(DstTy->getBitWidth() == SrcTy->getBitWidth() &&
667 "Casting packed to packed of different widths");
668 opcode = "bitcast"; // packed -> packed
669 } else if (DstTy->getBitWidth() == SrcBits) {
670 opcode = "bitcast"; // float/int -> packed
672 assert(!"Illegal cast to packed (wrong type or size)");
674 } else if (DstTy->isPointer()) {
675 if (SrcTy->isPointer()) {
676 opcode = "bitcast"; // ptr -> ptr
677 } else if (SrcTy->isIntegral()) {
678 opcode = "inttoptr"; // int -> ptr
680 assert(!"Casting invalid type to pointer");
683 assert(!"Casting to type that is not first-class");
688 std::string getCastUpgrade(const std::string& Src, const Type* SrcTy,
689 const Type* DstTy, bool isConst) {
691 std::string Source = Src;
692 if (SrcTy->isFloatingPoint() && DstTy->isPointer()) {
693 // fp -> ptr cast is no longer supported but we must upgrade this
694 // by doing a double cast: fp -> int -> ptr
696 Source = "i64 fptoui(" + Source + " to i64)";
698 *O << " %cast_upgrade" << UniqueNameCounter << " = fptoui "
699 << Source << " to i64\n";
700 Source = "i64 %cast_upgrade" + llvm::utostr(UniqueNameCounter++);
702 // Update the SrcTy for the getCastOpcode call below
703 SrcTy = Type::get("i64", ULongTy);
704 } else if (DstTy->isBool()) {
705 // cast type %x to bool was previously defined as setne type %x, null
706 // The cast semantic is now to truncate, not compare so we must retain
707 // the original intent by replacing the cast with a setne
708 const char* comparator = SrcTy->isPointer() ? ", null" :
709 (SrcTy->isFloatingPoint() ? ", 0.0" :
710 (SrcTy->isBool() ? ", false" : ", 0"));
711 const char* compareOp = SrcTy->isFloatingPoint() ? "fcmp one " : "icmp ne ";
713 Result = "(" + Source + comparator + ")";
714 Result = compareOp + Result;
716 Result = compareOp + Source + comparator;
717 return Result; // skip cast processing below
719 SrcTy = SrcTy->resolve();
720 DstTy = DstTy->resolve();
721 std::string Opcode(getCastOpcode(Source, SrcTy, DstTy));
723 Result += Opcode + "( " + Source + " to " + DstTy->getNewTy() + ")";
725 Result += Opcode + " " + Source + " to " + DstTy->getNewTy();
729 const char* getDivRemOpcode(const std::string& opcode, const Type* TI) {
730 const char* op = opcode.c_str();
731 const Type* Ty = TI->resolve();
733 Ty = Ty->getElementType();
735 if (Ty->isFloatingPoint())
737 else if (Ty->isUnsigned())
739 else if (Ty->isSigned())
742 yyerror("Invalid type for div instruction");
743 else if (opcode == "rem")
744 if (Ty->isFloatingPoint())
746 else if (Ty->isUnsigned())
748 else if (Ty->isSigned())
751 yyerror("Invalid type for rem instruction");
755 std::string getCompareOp(const std::string& setcc, const Type* TI) {
756 assert(setcc.length() == 5);
759 assert(cc1 == 'e' || cc1 == 'n' || cc1 == 'l' || cc1 == 'g');
760 assert(cc2 == 'q' || cc2 == 'e' || cc2 == 'e' || cc2 == 't');
761 std::string result("xcmp xxx");
764 if (TI->isFloatingPoint()) {
768 result[5] = 'u'; // NE maps to unordered
770 result[5] = 'o'; // everything else maps to ordered
771 } else if (TI->isIntegral() || TI->isPointer()) {
773 if ((cc1 == 'e' && cc2 == 'q') || (cc1 == 'n' && cc2 == 'e'))
775 else if (TI->isSigned())
777 else if (TI->isUnsigned() || TI->isPointer() || TI->isBool())
780 yyerror("Invalid integral type for setcc");
785 const Type* getFunctionReturnType(const Type* PFTy) {
786 PFTy = PFTy->resolve();
787 if (PFTy->isPointer()) {
788 const Type* ElemTy = PFTy->getElementType();
789 ElemTy = ElemTy->resolve();
790 if (ElemTy->isFunction())
791 return ElemTy->getResultType();
792 } else if (PFTy->isFunction()) {
793 return PFTy->getResultType();
798 const Type* ResolveUpReference(const Type* Ty,
799 Type::UpRefStack* stack) {
800 assert(Ty->isUpReference() && "Can't resolve a non-upreference");
801 unsigned upref = Ty->getUpRefNum();
802 assert(upref < stack->size() && "Invalid up reference");
803 return (*stack)[upref - stack->size() - 1];
806 const Type* getGEPIndexedType(const Type* PTy, ValueList* idxs) {
807 const Type* Result = PTy = PTy->resolve();
808 assert(PTy->isPointer() && "GEP Operand is not a pointer?");
809 Type::UpRefStack stack;
810 for (unsigned i = 0; i < idxs->size(); ++i) {
811 if (Result->isComposite()) {
812 Result = Result->getIndexedType((*idxs)[i]);
813 Result = Result->resolve();
814 stack.push_back(Result);
816 yyerror("Invalid type for index");
818 // Resolve upreferences so we can return a more natural type
819 if (Result->isPointer()) {
820 if (Result->getElementType()->isUpReference()) {
821 stack.push_back(Result);
822 Result = ResolveUpReference(Result->getElementType(), &stack);
824 } else if (Result->isUpReference()) {
825 Result = ResolveUpReference(Result->getElementType(), &stack);
827 return Result->getPointerType();
830 // This function handles appending .u or .s to integer value names that
831 // were previously unsigned or signed, respectively. This avoids name
832 // collisions since the unsigned and signed type planes have collapsed
833 // into a single signless type plane.
834 std::string getUniqueName(const std::string *Name, const Type* Ty,
835 bool isGlobal = false, bool isDef = false) {
837 // If its not a symbolic name, don't modify it, probably a constant val.
838 if ((*Name)[0] != '%' && (*Name)[0] != '"')
841 // If its a numeric reference, just leave it alone.
842 if (isdigit((*Name)[1]))
848 // If its a global name, get its uniquified name, if any
849 Type::GlobalsTypeMap::iterator GI = Type::Globals.find(*Name);
850 if (GI != Type::Globals.end()) {
851 Type::TypePlaneMap::iterator TPI = GI->second.begin();
852 Type::TypePlaneMap::iterator TPE = GI->second.end();
853 for ( ; TPI != TPE ; ++TPI) {
854 if (TPI->first->sameNewTyAs(Ty))
860 // We didn't find a global name, but if its supposed to be global then all
861 // we can do is return the name. This is probably a forward reference of a
862 // global value that hasn't been defined yet. Since we have no definition
863 // we don't know its linkage class. Just assume its an external and the name
868 // Default the result to the current name
869 std::string Result = Ty->makeUniqueName(*Name);
874 std::string getGlobalName(const std::string* Name, const std::string Linkage,
875 const Type* Ty, bool isConstant) {
876 // Default to given name
877 std::string Result = *Name;
878 // Look up the name in the Globals Map
879 Type::GlobalsTypeMap::iterator GI = Type::Globals.find(*Name);
880 // Did we see this global name before?
881 if (GI != Type::Globals.end()) {
882 if (Ty->isUnresolvedDeep()) {
883 // The Gval's type is unresolved. Consequently, we can't disambiguate it
884 // by type. We'll just change its name and emit a warning.
885 warning("Cannot disambiguate global value '" + *Name +
886 "' because type '" + Ty->getNewTy() + "'is unresolved.\n");
887 Result = *Name + ".unique";
889 Result += llvm::utostr(UniqueNameCounter);
892 Type::TypePlaneMap::iterator TPI = GI->second.find(Ty);
893 if (TPI != GI->second.end()) {
894 // We found an existing name of the same old type. This isn't allowed
895 // in LLVM 2.0. Consequently, we must alter the name of the global so it
896 // can at least compile. References to the global will yield the first
897 // definition, which is okay. We also must warn about this.
898 Result = *Name + ".unique";
900 Result += llvm::utostr(UniqueNameCounter);
901 warning(std::string("Global variable '") + *Name + "' was renamed to '"+
904 // There isn't an existing definition for this name according to the
905 // old types. Now search the TypePlanMap for types with the same new
907 Type::TypePlaneMap::iterator TPI = GI->second.begin();
908 Type::TypePlaneMap::iterator TPE = GI->second.end();
909 for ( ; TPI != TPE; ++TPI) {
910 if (TPI->first->sameNewTyAs(Ty)) {
911 // The new types are the same but the old types are different so
912 // this is a global name collision resulting from type planes
914 if (Linkage == "external" || Linkage == "dllimport" ||
915 Linkage == "extern_weak" || Linkage == "") {
916 // The linkage of this gval is external so we can't reliably
917 // rename it because it could potentially create a linking
918 // problem. However, we can't leave the name conflict in the
919 // output either or it won't assemble with LLVM 2.0. So, all we
920 // can do is rename this one to something unique and emit a
921 // warning about the problem.
922 Result = *Name + ".unique";
924 Result += llvm::utostr(UniqueNameCounter);
925 warning("Renaming global value '" + *Name + "' to '" + Result +
926 "' may cause linkage errors.");
929 // Its linkage is internal and its type is known so we can
930 // disambiguate the name collision successfully based on the type.
931 Result = getUniqueName(Name, Ty);
932 TPI->second = Result;
937 // We didn't find an entry in the type plane with the same new type and
938 // the old types differ so this is a new type plane for this global
939 // variable. We just fall through to the logic below which inserts
945 // Its a new global name, if it is external we can't change it
946 if (isConstant || Linkage == "external" || Linkage == "dllimport" ||
947 Linkage == "extern_weak" || Linkage == "") {
948 Type::Globals[Result][Ty] = Result;
952 // Its a new global name, and it is internal, change the name to make it
953 // unique for its type.
954 // Result = getUniqueName(Name, Ty);
955 Type::Globals[*Name][Ty] = Result;
959 } // End anonymous namespace
961 // This function is used by the Lexer to create a Type. It can't be
962 // in the anonymous namespace.
963 const Type* getType(const std::string& newTy, TypeIDs oldTy) {
964 return Type::get(newTy, oldTy);
969 // %file-prefix="UpgradeParser"
980 %token <Ty> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
981 %token <Ty> FLOAT DOUBLE LABEL
982 %token <String> OPAQUE ESINT64VAL EUINT64VAL SINTVAL UINTVAL FPVAL
983 %token <String> NULL_TOK UNDEF ZEROINITIALIZER TRUETOK FALSETOK
984 %token <String> TYPE VAR_ID LABELSTR STRINGCONSTANT
985 %token <String> IMPLEMENTATION BEGINTOK ENDTOK
986 %token <String> DECLARE GLOBAL CONSTANT SECTION VOLATILE
987 %token <String> TO DOTDOTDOT CONST INTERNAL LINKONCE WEAK
988 %token <String> DLLIMPORT DLLEXPORT EXTERN_WEAK APPENDING
989 %token <String> EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG
990 %token <String> ALIGN UNINITIALIZED
991 %token <String> DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
992 %token <String> CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
993 %token <String> X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
994 %token <String> DATALAYOUT
995 %token <String> RET BR SWITCH INVOKE EXCEPT UNWIND UNREACHABLE
996 %token <String> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM AND OR XOR
997 %token <String> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
998 %token <String> ICMP FCMP EQ NE SLT SGT SLE SGE OEQ ONE OLT OGT OLE OGE
999 %token <String> ORD UNO UEQ UNE ULT UGT ULE UGE
1000 %token <String> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1001 %token <String> PHI_TOK SELECT SHL SHR ASHR LSHR VAARG
1002 %token <String> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1003 %token <String> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI UITOFP SITOFP
1004 %token <String> PTRTOINT INTTOPTR BITCAST
1006 %type <String> OptAssign OptLinkage OptCallingConv OptAlign OptCAlign
1007 %type <String> SectionString OptSection GlobalVarAttributes GlobalVarAttribute
1008 %type <String> ConstExpr DefinitionList
1009 %type <String> ConstPool TargetDefinition LibrariesDefinition LibList OptName
1010 %type <String> ArgVal ArgListH ArgList FunctionHeaderH BEGIN FunctionHeader END
1011 %type <String> Function FunctionProto BasicBlock
1012 %type <String> InstructionList BBTerminatorInst JumpTable Inst
1013 %type <String> OptTailCall OptVolatile Unwind
1014 %type <String> SymbolicValueRef OptSideEffect GlobalType
1015 %type <String> FnDeclareLinkage BasicBlockList BigOrLittle AsmBlock
1016 %type <String> Name ConstValueRef ConstVector External
1017 %type <String> ShiftOps SetCondOps LogicalOps ArithmeticOps CastOps
1018 %type <String> IPredicates FPredicates
1020 %type <ValList> ValueRefList ValueRefListE IndexList
1021 %type <TypeVec> TypeListI ArgTypeListI
1023 %type <Ty> IntType SIntType UIntType FPType TypesV Types
1024 %type <Ty> PrimType UpRTypesV UpRTypes
1026 %type <String> IntVal EInt64Val
1027 %type <Const> ConstVal
1029 %type <Val> ValueRef ResolvedVal InstVal PHIList MemoryInst
1035 // Handle constant integer size restriction and conversion...
1036 IntVal : SINTVAL | UINTVAL ;
1037 EInt64Val : ESINT64VAL | EUINT64VAL;
1039 // Operations that are notably excluded from this list include:
1040 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1041 ArithmeticOps: ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV
1042 | REM | UREM | SREM | FREM;
1043 LogicalOps : AND | OR | XOR;
1044 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1045 IPredicates : EQ | NE | SLT | SGT | SLE | SGE | ULT | UGT | ULE | UGE;
1046 FPredicates : OEQ | ONE | OLT | OGT | OLE | OGE | ORD | UNO | UEQ | UNE
1047 | ULT | UGT | ULE | UGE | TRUETOK | FALSETOK;
1048 ShiftOps : SHL | SHR | ASHR | LSHR;
1049 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI |
1050 UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1053 // These are some types that allow classification if we only want a particular
1054 // thing... for example, only a signed, unsigned, or integral type.
1055 SIntType : LONG | INT | SHORT | SBYTE;
1056 UIntType : ULONG | UINT | USHORT | UBYTE;
1057 IntType : SIntType | UIntType;
1058 FPType : FLOAT | DOUBLE;
1060 // OptAssign - Value producing statements have an optional assignment component
1061 OptAssign : Name '=' {
1065 $$ = new std::string("");
1069 : INTERNAL | LINKONCE | WEAK | APPENDING | DLLIMPORT | DLLEXPORT
1071 | /*empty*/ { $$ = new std::string(""); } ;
1074 : CCC_TOK | CSRETCC_TOK | FASTCC_TOK | COLDCC_TOK | X86_STDCALLCC_TOK
1075 | X86_FASTCALLCC_TOK
1076 | CC_TOK EUINT64VAL {
1081 | /*empty*/ { $$ = new std::string(""); } ;
1083 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1084 // a comma before it.
1086 : /*empty*/ { $$ = new std::string(); }
1087 | ALIGN EUINT64VAL { *$1 += " " + *$2; delete $2; $$ = $1; };
1090 : /*empty*/ { $$ = new std::string(); }
1091 | ',' ALIGN EUINT64VAL {
1092 $2->insert(0, ", ");
1099 : SECTION STRINGCONSTANT {
1105 OptSection : /*empty*/ { $$ = new std::string(); }
1109 : /* empty */ { $$ = new std::string(); }
1110 | ',' GlobalVarAttribute GlobalVarAttributes {
1111 $2->insert(0, ", ");
1120 | ALIGN EUINT64VAL {
1126 //===----------------------------------------------------------------------===//
1127 // Types includes all predefined types... except void, because it can only be
1128 // used in specific contexts (function returning void for example). To have
1129 // access to it, a user must explicitly use TypesV.
1132 // TypesV includes all of 'Types', but it also includes the void type.
1133 TypesV : Types | VOID ;
1134 UpRTypesV : UpRTypes | VOID ;
1137 // Derived types are added later...
1139 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
1140 PrimType : LONG | ULONG | FLOAT | DOUBLE | LABEL;
1143 $$ = Type::get(*$1, OpaqueTy);
1145 | SymbolicValueRef {
1146 $$ = Type::get(*$1, UnresolvedTy);
1151 | '\\' EUINT64VAL { // Type UpReference
1152 $2->insert(0, "\\");
1153 $$ = Type::get(*$2, UpRefTy);
1155 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1156 std::string newTy( $1->getNewTy() + "(");
1157 for (unsigned i = 0; i < $3->size(); ++i) {
1160 if ((*$3)[i]->isVoid())
1163 newTy += (*$3)[i]->getNewTy();
1166 $$ = Type::get(newTy, $1, $3);
1168 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1169 uint64_t elems = atoi($2->c_str());
1171 *$2 += " x " + $4->getNewTy() + " ]";
1172 $$ = Type::get(*$2, ArrayTy, $4, elems);
1174 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1175 uint64_t elems = atoi($2->c_str());
1177 *$2 += " x " + $4->getNewTy() + " >";
1178 $$ = Type::get(*$2, PackedTy, $4, elems);
1180 | '{' TypeListI '}' { // Structure type?
1181 std::string newTy("{");
1182 for (unsigned i = 0; i < $2->size(); ++i) {
1185 newTy += (*$2)[i]->getNewTy();
1188 $$ = Type::get(newTy, StructTy, $2);
1190 | '{' '}' { // Empty structure type?
1191 $$ = Type::get("{}", StructTy, new TypeList());
1193 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
1194 std::string newTy("<{");
1195 for (unsigned i = 0; i < $3->size(); ++i) {
1198 newTy += (*$3)[i]->getNewTy();
1201 $$ = Type::get(newTy, PackedStructTy, $3);
1203 | '<' '{' '}' '>' { // Empty packed structure type?
1204 $$ = Type::get("<{}>", PackedStructTy, new TypeList());
1206 | UpRTypes '*' { // Pointer type?
1207 $$ = $1->getPointerType();
1210 // TypeList - Used for struct declarations and as a basis for function type
1211 // declaration type lists
1215 $$ = new TypeList();
1218 | TypeListI ',' UpRTypes {
1223 // ArgTypeList - List of types for a function type declaration...
1226 | TypeListI ',' DOTDOTDOT {
1228 $$->push_back(Type::get("void",VoidTy));
1232 $$ = new TypeList();
1233 $$->push_back(Type::get("void",VoidTy));
1237 $$ = new TypeList();
1240 // ConstVal - The various declarations that go into the constant pool. This
1241 // production is used ONLY to represent constants that show up AFTER a 'const',
1242 // 'constant' or 'global' token at global scope. Constants that can be inlined
1243 // into other expressions (such as integers and constexprs) are handled by the
1244 // ResolvedVal, ValueRef and ConstValueRef productions.
1246 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1249 $$->cnst = new std::string($1->getNewTy());
1250 *$$->cnst += " [ " + *$3 + " ]";
1256 $$->cnst = new std::string($1->getNewTy());
1259 | Types 'c' STRINGCONSTANT {
1262 $$->cnst = new std::string($1->getNewTy());
1263 *$$->cnst += " c" + *$3;
1266 | Types '<' ConstVector '>' { // Nonempty unsized arr
1269 $$->cnst = new std::string($1->getNewTy());
1270 *$$->cnst += " < " + *$3 + " >";
1273 | Types '{' ConstVector '}' {
1276 $$->cnst = new std::string($1->getNewTy());
1277 *$$->cnst += " { " + *$3 + " }";
1283 $$->cnst = new std::string($1->getNewTy());
1289 $$->cnst = new std::string($1->getNewTy());
1290 *$$->cnst += " " + *$2;
1296 $$->cnst = new std::string($1->getNewTy());
1297 *$$->cnst += " " + *$2;
1300 | Types SymbolicValueRef {
1302 std::string Name = getUniqueName($2, $1->resolve(), true);
1304 $$->cnst = new std::string($1->getNewTy());
1305 *$$->cnst += " " + Name;
1311 $$->cnst = new std::string($1->getNewTy());
1312 *$$->cnst += " " + *$2;
1315 | Types ZEROINITIALIZER {
1318 $$->cnst = new std::string($1->getNewTy());
1319 *$$->cnst += " " + *$2;
1322 | SIntType EInt64Val { // integral constants
1325 $$->cnst = new std::string($1->getNewTy());
1326 *$$->cnst += " " + *$2;
1329 | UIntType EInt64Val { // integral constants
1332 $$->cnst = new std::string($1->getNewTy());
1333 *$$->cnst += " " + *$2;
1336 | BOOL TRUETOK { // Boolean constants
1339 $$->cnst = new std::string($1->getNewTy());
1340 *$$->cnst += " " + *$2;
1343 | BOOL FALSETOK { // Boolean constants
1346 $$->cnst = new std::string($1->getNewTy());
1347 *$$->cnst += " " + *$2;
1350 | FPType FPVAL { // Float & Double constants
1353 $$->cnst = new std::string($1->getNewTy());
1354 *$$->cnst += " " + *$2;
1358 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1359 std::string source = *$3->cnst;
1360 const Type* SrcTy = $3->type->resolve();
1361 const Type* DstTy = $5->resolve();
1362 if (*$1 == "cast") {
1363 // Call getCastUpgrade to upgrade the old cast
1364 $$ = new std::string(getCastUpgrade(source, SrcTy, DstTy, true));
1366 // Nothing to upgrade, just create the cast constant expr
1367 $$ = new std::string(*$1);
1368 *$$ += "( " + source + " to " + $5->getNewTy() + ")";
1370 delete $1; delete $3; delete $4;
1372 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1373 *$1 += "(" + *$3->cnst;
1374 for (unsigned i = 0; i < $4->size(); ++i) {
1375 Value* V = (*$4)[i];
1376 *$1 += ", " + *V->val;
1384 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1385 *$1 += "(" + *$3->cnst + "," + *$5->cnst + "," + *$7->cnst + ")";
1386 delete $3; delete $5; delete $7;
1389 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1390 const char* op = getDivRemOpcode(*$1, $3->type);
1391 $$ = new std::string(op);
1392 *$$ += "(" + *$3->cnst + "," + *$5->cnst + ")";
1393 delete $1; delete $3; delete $5;
1395 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1396 *$1 += "(" + *$3->cnst + "," + *$5->cnst + ")";
1397 delete $3; delete $5;
1400 | SetCondOps '(' ConstVal ',' ConstVal ')' {
1401 *$1 = getCompareOp(*$1, $3->type);
1402 *$1 += "(" + *$3->cnst + "," + *$5->cnst + ")";
1403 delete $3; delete $5;
1406 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1407 *$1 += " " + *$2 + " (" + *$4->cnst + "," + *$6->cnst + ")";
1408 delete $2; delete $4; delete $6;
1411 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1412 *$1 += " " + *$2 + " (" + *$4->cnst + "," + *$6->cnst + ")";
1413 delete $2; delete $4; delete $6;
1416 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1417 const char* shiftop = $1->c_str();
1419 shiftop = ($3->type->isUnsigned()) ? "lshr" : "ashr";
1420 $$ = new std::string(shiftop);
1421 *$$ += "(" + *$3->cnst + "," + *$5->cnst + ")";
1422 delete $1; delete $3; delete $5;
1424 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1425 *$1 += "(" + *$3->cnst + "," + *$5->cnst + ")";
1426 delete $3; delete $5;
1429 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1430 *$1 += "(" + *$3->cnst + "," + *$5->cnst + "," + *$7->cnst + ")";
1431 delete $3; delete $5; delete $7;
1434 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1435 *$1 += "(" + *$3->cnst + "," + *$5->cnst + "," + *$7->cnst + ")";
1436 delete $3; delete $5; delete $7;
1441 // ConstVector - A list of comma separated constants.
1444 : ConstVector ',' ConstVal {
1445 *$1 += ", " + *$3->cnst;
1449 | ConstVal { $$ = new std::string(*$1->cnst); delete $1; }
1453 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1454 GlobalType : GLOBAL | CONSTANT ;
1457 //===----------------------------------------------------------------------===//
1458 // Rules to match Modules
1459 //===----------------------------------------------------------------------===//
1461 // Module rule: Capture the result of parsing the whole file into a result
1464 Module : DefinitionList {
1467 // DefinitionList - Top level definitions
1469 DefinitionList : DefinitionList Function {
1472 | DefinitionList FunctionProto {
1477 | DefinitionList MODULE ASM_TOK AsmBlock {
1478 *O << "module asm " << ' ' << *$4 << '\n';
1481 | DefinitionList IMPLEMENTATION {
1482 *O << "implementation\n";
1485 | ConstPool { $$ = 0; }
1487 External : EXTERNAL | UNINITIALIZED { $$ = $1; *$$ = "external"; }
1489 // ConstPool - Constants with optional names assigned to them.
1490 ConstPool : ConstPool OptAssign TYPE TypesV {
1491 Type::EnumeratedTypes.push_back($4);
1493 Type::NamedTypes[*$2] = $4;
1496 *O << "type " << $4->getNewTy() << '\n';
1497 delete $2; delete $3;
1500 | ConstPool FunctionProto { // Function prototypes can be in const pool
1505 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
1506 *O << *$2 << ' ' << *$3 << ' ' << *$4 << '\n';
1507 delete $2; delete $3; delete $4;
1510 | ConstPool OptAssign OptLinkage GlobalType ConstVal GlobalVarAttributes {
1512 std::string Name = getGlobalName($2,*$3, $5->type->getPointerType(),
1514 *O << Name << " = ";
1516 *O << *$3 << ' ' << *$4 << ' ' << *$5->cnst << ' ' << *$6 << '\n';
1517 delete $2; delete $3; delete $4; delete $6;
1520 | ConstPool OptAssign External GlobalType Types GlobalVarAttributes {
1522 std::string Name = getGlobalName($2,*$3,$5->getPointerType(),
1524 *O << Name << " = ";
1526 *O << *$3 << ' ' << *$4 << ' ' << $5->getNewTy() << ' ' << *$6 << '\n';
1527 delete $2; delete $3; delete $4; delete $6;
1530 | ConstPool OptAssign DLLIMPORT GlobalType Types GlobalVarAttributes {
1532 std::string Name = getGlobalName($2,*$3,$5->getPointerType(),
1534 *O << Name << " = ";
1536 *O << *$3 << ' ' << *$4 << ' ' << $5->getNewTy() << ' ' << *$6 << '\n';
1537 delete $2; delete $3; delete $4; delete $6;
1540 | ConstPool OptAssign EXTERN_WEAK GlobalType Types GlobalVarAttributes {
1542 std::string Name = getGlobalName($2,*$3,$5->getPointerType(),
1544 *O << Name << " = ";
1546 *O << *$3 << ' ' << *$4 << ' ' << $5->getNewTy() << ' ' << *$6 << '\n';
1547 delete $2; delete $3; delete $4; delete $6;
1550 | ConstPool TARGET TargetDefinition {
1551 *O << *$2 << ' ' << *$3 << '\n';
1552 delete $2; delete $3;
1555 | ConstPool DEPLIBS '=' LibrariesDefinition {
1556 *O << *$2 << " = " << *$4 << '\n';
1557 delete $2; delete $4;
1560 | /* empty: end of list */ {
1565 AsmBlock : STRINGCONSTANT ;
1567 BigOrLittle : BIG | LITTLE
1570 : ENDIAN '=' BigOrLittle {
1575 | POINTERSIZE '=' EUINT64VAL {
1582 | TRIPLE '=' STRINGCONSTANT {
1587 | DATALAYOUT '=' STRINGCONSTANT {
1595 $2->insert(0, "[ ");
1601 : LibList ',' STRINGCONSTANT {
1607 | /* empty: end of list */ {
1608 $$ = new std::string();
1611 //===----------------------------------------------------------------------===//
1612 // Rules to match Function Headers
1613 //===----------------------------------------------------------------------===//
1615 Name : VAR_ID | STRINGCONSTANT;
1616 OptName : Name | /*empty*/ { $$ = new std::string(); };
1618 ArgVal : Types OptName {
1619 $$ = new std::string($1->getNewTy());
1621 std::string Name = getUniqueName($2, $1->resolve());
1627 ArgListH : ArgListH ',' ArgVal {
1635 ArgList : ArgListH {
1638 | ArgListH ',' DOTDOTDOT {
1646 | /* empty */ { $$ = new std::string(); };
1649 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
1650 if (*$3 == "%llvm.va_start" || *$3 == "%llvm.va_end") {
1652 } else if (*$3 == "%llvm.va_copy") {
1658 *$1 += $2->getNewTy() + " " + *$3 + "(" + *$5 + ")";
1672 BEGIN : BEGINTOK { $$ = new std::string("{"); delete $1; }
1673 | '{' { $$ = new std::string ("{"); }
1676 : OptLinkage FunctionHeaderH BEGIN {
1681 *O << *$2 << ' ' << *$3 << '\n';
1682 delete $1; delete $2; delete $3;
1687 END : ENDTOK { $$ = new std::string("}"); delete $1; }
1688 | '}' { $$ = new std::string("}"); };
1690 Function : FunctionHeader BasicBlockList END {
1693 *O << *$3 << "\n\n";
1694 delete $1; delete $2; delete $3;
1699 : /*default*/ { $$ = new std::string(); }
1705 : DECLARE { isDeclare = true; } FnDeclareLinkage FunctionHeaderH {
1715 //===----------------------------------------------------------------------===//
1716 // Rules to match Basic Blocks
1717 //===----------------------------------------------------------------------===//
1719 OptSideEffect : /* empty */ { $$ = new std::string(); }
1723 : ESINT64VAL | EUINT64VAL | FPVAL | TRUETOK | FALSETOK | NULL_TOK | UNDEF
1725 | '<' ConstVector '>' {
1731 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
1735 *$1 += " " + *$3 + ", " + *$5;
1736 delete $2; delete $3; delete $5;
1740 SymbolicValueRef : IntVal | Name ;
1742 // ValueRef - A reference to a definition... either constant or symbolic
1744 : SymbolicValueRef {
1747 $$->constant = false;
1753 $$->constant = true;
1758 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1759 // type immediately preceeds the value reference, and allows complex constant
1760 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1761 ResolvedVal : Types ValueRef {
1763 std::string Name = getUniqueName($2->val, $1);
1766 $$->val = new std::string($1->getNewTy() + " " + Name);
1770 BasicBlockList : BasicBlockList BasicBlock {
1773 | BasicBlock { // Do not allow functions with 0 basic blocks
1778 // Basic blocks are terminated by branching instructions:
1779 // br, br/cc, switch, ret
1781 BasicBlock : InstructionList BBTerminatorInst {
1785 InstructionList : InstructionList Inst {
1786 *O << " " << *$2 << '\n';
1799 Unwind : UNWIND | EXCEPT { $$ = $1; *$$ = "unwind"; }
1801 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1802 *O << " " << *$1 << ' ' << *$2->val << '\n';
1803 delete $1; delete $2;
1806 | RET VOID { // Return with no result...
1807 *O << " " << *$1 << ' ' << $2->getNewTy() << '\n';
1811 | BR LABEL ValueRef { // Unconditional Branch...
1812 *O << " " << *$1 << ' ' << $2->getNewTy() << ' ' << *$3->val << '\n';
1813 delete $1; delete $3;
1815 } // Conditional Branch...
1816 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1817 std::string Name = getUniqueName($3->val, $2);
1818 *O << " " << *$1 << ' ' << $2->getNewTy() << ' ' << Name << ", "
1819 << $5->getNewTy() << ' ' << *$6->val << ", " << $8->getNewTy() << ' '
1820 << *$9->val << '\n';
1821 delete $1; delete $3; delete $6; delete $9;
1824 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1825 std::string Name = getUniqueName($3->val, $2);
1826 *O << " " << *$1 << ' ' << $2->getNewTy() << ' ' << Name << ", "
1827 << $5->getNewTy() << ' ' << *$6->val << " [" << *$8 << " ]\n";
1834 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1835 std::string Name = getUniqueName($3->val, $2);
1836 *O << " " << *$1 << ' ' << $2->getNewTy() << ' ' << Name << ", "
1837 << $5->getNewTy() << ' ' << *$6->val << "[]\n";
1843 | OptAssign INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
1844 TO LABEL ValueRef Unwind LABEL ValueRef {
1845 const Type* ResTy = getFunctionReturnType($4);
1848 std::string Name = getUniqueName($1, ResTy);
1849 *O << Name << " = ";
1851 *O << *$2 << ' ' << *$3 << ' ' << $4->getNewTy() << ' ' << *$5->val << " (";
1852 for (unsigned i = 0; i < $7->size(); ++i) {
1853 Value* V = (*$7)[i];
1855 if (i+1 < $7->size())
1859 *O << ") " << *$9 << ' ' << $10->getNewTy() << ' ' << *$11->val << ' '
1860 << *$12 << ' ' << $13->getNewTy() << ' ' << *$14->val << '\n';
1861 delete $1; delete $2; delete $3; delete $5; delete $7;
1862 delete $9; delete $11; delete $12; delete $14;
1866 *O << " " << *$1 << '\n';
1871 *O << " " << *$1 << '\n';
1876 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1877 *$1 += " " + $2->getNewTy() + " " + *$3 + ", " + $5->getNewTy() + " " +
1879 delete $3; delete $6;
1882 | IntType ConstValueRef ',' LABEL ValueRef {
1883 $2->insert(0, $1->getNewTy() + " " );
1884 *$2 += ", " + $4->getNewTy() + " " + *$5->val;
1890 : OptAssign InstVal {
1892 // Get a unique name for this value, based on its type.
1893 std::string Name = getUniqueName($1, $2->type);
1895 if (deleteUselessCastFlag && *deleteUselessCastName == Name) {
1896 // don't actually delete it, just comment it out
1897 $1->insert(0, "; USELSS BITCAST: ");
1898 delete deleteUselessCastName;
1903 deleteUselessCastFlag = false;
1908 : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1909 std::string Name = getUniqueName($3->val, $1);
1910 Name.insert(0, $1->getNewTy() + "[");
1911 Name += "," + *$5->val + "]";
1913 $$->val = new std::string(Name);
1915 delete $3; delete $5;
1917 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1918 std::string Name = getUniqueName($4->val, $1->type);
1919 *$1->val += ", [" + Name + "," + *$6->val + "]";
1928 $$ = new ValueList();
1931 | ValueRefList ',' ResolvedVal {
1936 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1938 : ValueRefList { $$ = $1; }
1939 | /*empty*/ { $$ = new ValueList(); }
1951 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1952 const char* op = getDivRemOpcode(*$1, $2);
1953 std::string Name1 = getUniqueName($3->val, $2);
1954 std::string Name2 = getUniqueName($5->val, $2);
1957 $$->val = new std::string(op);
1958 *$$->val += " " + $2->getNewTy() + " " + Name1 + ", " + Name2;
1960 delete $1; delete $5;
1962 | LogicalOps Types ValueRef ',' ValueRef {
1963 std::string Name1 = getUniqueName($3->val, $2);
1964 std::string Name2 = getUniqueName($5->val, $2);
1965 *$1 += " " + $2->getNewTy() + " " + Name1 + ", " + Name2;
1972 | SetCondOps Types ValueRef ',' ValueRef {
1973 std::string Name1 = getUniqueName($3->val, $2);
1974 std::string Name2 = getUniqueName($5->val, $2);
1975 *$1 = getCompareOp(*$1, $2);
1976 *$1 += " " + $2->getNewTy() + " " + Name1 + ", " + Name2;
1980 $$->type = Type::get("i1",BoolTy);
1983 | ICMP IPredicates Types ValueRef ',' ValueRef {
1984 std::string Name1 = getUniqueName($4->val, $3);
1985 std::string Name2 = getUniqueName($6->val, $3);
1986 *$1 += " " + *$2 + " " + $3->getNewTy() + " " + Name1 + "," + Name2;
1990 $$->type = Type::get("i1",BoolTy);
1991 delete $2; delete $6;
1993 | FCMP FPredicates Types ValueRef ',' ValueRef {
1994 std::string Name1 = getUniqueName($4->val, $3);
1995 std::string Name2 = getUniqueName($6->val, $3);
1996 *$1 += " " + *$2 + " " + $3->getNewTy() + " " + Name1 + "," + Name2;
2000 $$->type = Type::get("i1",BoolTy);
2001 delete $2; delete $6;
2003 | ShiftOps ResolvedVal ',' ResolvedVal {
2004 const char* shiftop = $1->c_str();
2006 shiftop = ($2->type->isUnsigned()) ? "lshr" : "ashr";
2007 std::string *val = new std::string(shiftop);
2008 *val += " " + *$2->val + ", " + *$4->val;
2012 delete $1; delete $4;
2014 | CastOps ResolvedVal TO Types {
2015 std::string source = *$2->val;
2016 const Type* SrcTy = $2->type->resolve();
2017 const Type* DstTy = $4->resolve();
2020 $$->val = new std::string();
2022 if (*$1 == "cast") {
2023 *$$->val += getCastUpgrade(source, SrcTy, DstTy, false);
2025 *$$->val += *$1 + " " + source + " to " + DstTy->getNewTy();
2027 // Check to see if this is a useless cast of a value to the same name
2028 // and the same type. Such casts will probably cause redefinition errors
2029 // when assembled and perform no code gen action so just remove them.
2030 if (*$1 == "cast" || *$1 == "bitcast")
2031 if (SrcTy->isInteger() && DstTy->isInteger() &&
2032 SrcTy->getBitWidth() == DstTy->getBitWidth()) {
2033 deleteUselessCastFlag = true; // Flag the "Inst" rule
2034 deleteUselessCastName = new std::string(*$2->val); // save the name
2035 size_t pos = deleteUselessCastName->find_first_of("%\"",0);
2036 if (pos != std::string::npos) {
2037 // remove the type portion before val
2038 deleteUselessCastName->erase(0, pos);
2044 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2045 *$1 += " " + *$2->val + ", " + *$4->val + ", " + *$6->val;
2049 $$->type = $4->type;
2053 | VAARG ResolvedVal ',' Types {
2054 *$1 += " " + *$2->val + ", " + $4->getNewTy();
2060 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2061 *$1 += " " + *$2->val + ", " + *$4->val;
2065 $$->type = $$->type->resolve();
2066 $$->type = $$->type->getElementType();
2069 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2070 *$1 += " " + *$2->val + ", " + *$4->val + ", " + *$6->val;
2074 delete $4; delete $6;
2076 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2077 *$1 += " " + *$2->val + ", " + *$4->val + ", " + *$6->val;
2081 delete $4; delete $6;
2084 *$1 += " " + *$2->val;
2089 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
2090 // map llvm.isunordered to "fcmp uno"
2092 if (*$4->val == "%llvm.isunordered.f32" ||
2093 *$4->val == "%llvm.isunordered.f64") {
2094 $$->val = new std::string( "fcmp uno " + *(*$6)[0]->val + ", ");
2095 size_t pos = (*$6)[1]->val->find(' ');
2096 assert(pos != std::string::npos && "no space?");
2097 *$$->val += (*$6)[1]->val->substr(pos+1);
2098 $$->type = Type::get("i1", BoolTy);
2100 static unsigned upgradeCount = 1;
2101 if (*$4->val == "%llvm.va_start" || *$4->val == "%llvm.va_end") {
2103 std::string name("%va_upgrade");
2104 name += llvm::utostr(upgradeCount++);
2105 $1->insert(0, name + " = bitcast " + *(*$6)[0]->val + " to i8*\n ");
2106 *(*$6)[0]->val = "i8* " + name;
2107 (*$6)[0]->type = Type::get("i8", UByteTy)->getPointerType();
2109 } else if (*$4->val == "%llvm.va_copy") {
2110 std::string name0("%va_upgrade");
2111 name0 += llvm::utostr(upgradeCount++);
2112 std::string name1("%va_upgrade");
2113 name1 += llvm::utostr(upgradeCount++);
2114 $1->insert(0, name0 + " = bitcast " + *(*$6)[0]->val + " to i8*\n " +
2115 name1 + " = bitcast " + *(*$6)[1]->val + " to i8*\n ");
2116 *(*$6)[0]->val = "i8* " + name0;
2117 (*$6)[0]->type = Type::get("i8", UByteTy)->getPointerType();
2118 *(*$6)[1]->val = "i8* " + name1;
2119 (*$6)[0]->type = Type::get("i8", UByteTy)->getPointerType();
2125 *$1 += $3->getNewTy() + " " + *$4->val + "(";
2126 for (unsigned i = 0; i < $6->size(); ++i) {
2127 Value* V = (*$6)[i];
2129 if (i+1 < $6->size())
2136 $$->type = getFunctionReturnType($3);
2138 delete $2; delete $4; delete $6;
2143 // IndexList - List of indices for GEP based instructions...
2145 : ',' ValueRefList { $$ = $2; }
2146 | /* empty */ { $$ = new ValueList(); }
2151 | /* empty */ { $$ = new std::string(); }
2154 MemoryInst : MALLOC Types OptCAlign {
2155 *$1 += " " + $2->getNewTy();
2160 $$->type = $2->getPointerType();
2163 | MALLOC Types ',' UINT ValueRef OptCAlign {
2164 std::string Name = getUniqueName($5->val, $4);
2165 *$1 += " " + $2->getNewTy() + ", " + $4->getNewTy() + " " + Name;
2170 $$->type = $2->getPointerType();
2171 delete $5; delete $6;
2173 | ALLOCA Types OptCAlign {
2174 *$1 += " " + $2->getNewTy();
2179 $$->type = $2->getPointerType();
2182 | ALLOCA Types ',' UINT ValueRef OptCAlign {
2183 std::string Name = getUniqueName($5->val, $4);
2184 *$1 += " " + $2->getNewTy() + ", " + $4->getNewTy() + " " + Name;
2190 $$->type = $2->getPointerType();
2193 | FREE ResolvedVal {
2194 *$1 += " " + *$2->val;
2198 $$->type = Type::get("void", VoidTy);
2200 | OptVolatile LOAD Types ValueRef {
2201 std::string Name = getUniqueName($4->val, $3);
2204 *$1 += *$2 + " " + $3->getNewTy() + " " + Name;
2208 $$->type = $3->getElementType();
2211 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2212 std::string Name = getUniqueName($6->val, $5);
2215 *$1 += *$2 + " " + *$3->val + ", " + $5->getNewTy() + " " + Name;
2219 $$->type = Type::get("void", VoidTy);
2220 delete $2; delete $6;
2222 | GETELEMENTPTR Types ValueRef IndexList {
2223 std::string Name = getUniqueName($3->val, $2);
2224 // Upgrade the indices
2225 for (unsigned i = 0; i < $4->size(); ++i) {
2226 Value* V = (*$4)[i];
2227 if (V->type->isUnsigned() && !V->isConstant() &&
2228 V->type->getBitWidth() < 64) {
2229 *O << " %gep_upgrade" << UniqueNameCounter << " = zext " << *V->val
2231 *V->val = "i64 %gep_upgrade" + llvm::utostr(UniqueNameCounter++);
2232 V->type = Type::get("i64",ULongTy);
2235 *$1 += " " + $2->getNewTy() + " " + Name;
2236 for (unsigned i = 0; i < $4->size(); ++i) {
2237 Value* V = (*$4)[i];
2238 *$1 += ", " + *V->val;
2243 $$->type = getGEPIndexedType($2,$4);
2244 for (unsigned i = 0; i < $4->size(); ++i)
2251 int yyerror(const char *ErrorMsg) {
2253 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2254 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
2255 std::string errMsg = where + "error: " + std::string(ErrorMsg) +
2257 if (yychar == YYEMPTY || yychar == 0)
2258 errMsg += "end-of-file.";
2260 errMsg += "token: '" + std::string(Upgradetext, Upgradeleng) + "'";
2261 std::cerr << "llvm-upgrade: " << errMsg << '\n';
2262 *O << "llvm-upgrade parse failed.\n";
2266 void warning(const std::string& ErrorMsg) {
2268 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2269 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
2270 std::string errMsg = where + "warning: " + std::string(ErrorMsg) +
2272 if (yychar == YYEMPTY || yychar == 0)
2273 errMsg += "end-of-file.";
2275 errMsg += "token: '" + std::string(Upgradetext, Upgradeleng) + "'";
2276 std::cerr << "llvm-upgrade: " << errMsg << '\n';