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 "UpgradeInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/SymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/MathExtras.h"
29 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
30 // relating to upreferences in the input stream.
32 //#define DEBUG_UPREFS 1
34 #define UR_OUT(X) std::cerr << X
39 #define YYERROR_VERBOSE 1
40 #define YYINCLUDED_STDLIB_H
46 int yyerror(const char*);
47 static void warning(const std::string& WarningMsg);
51 std::istream* LexInput;
52 static std::string CurFilename;
54 // This bool controls whether attributes are ever added to function declarations
55 // definitions and calls.
56 static bool AddAttributes = false;
58 static Module *ParserResult;
59 static bool ObsoleteVarArgs;
60 static bool NewVarArgs;
61 static BasicBlock *CurBB;
62 static GlobalVariable *CurGV;
64 // This contains info used when building the body of a function. It is
65 // destroyed when the function is completed.
67 typedef std::vector<Value *> ValueList; // Numbered defs
69 typedef std::pair<std::string,const Type*> RenameMapKey;
70 typedef std::map<RenameMapKey,std::string> RenameMapType;
73 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
74 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
76 static struct PerModuleInfo {
77 Module *CurrentModule;
78 std::map<const Type *, ValueList> Values; // Module level numbered definitions
79 std::map<const Type *,ValueList> LateResolveValues;
80 std::vector<PATypeHolder> Types;
81 std::map<ValID, PATypeHolder> LateResolveTypes;
82 static Module::Endianness Endian;
83 static Module::PointerSize PointerSize;
84 RenameMapType RenameMap;
86 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
87 /// how they were referenced and on which line of the input they came from so
88 /// that we can resolve them later and print error messages as appropriate.
89 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
91 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
92 // references to global values. Global values may be referenced before they
93 // are defined, and if so, the temporary object that they represent is held
94 // here. This is used for forward references of GlobalValues.
96 typedef std::map<std::pair<const PointerType *, ValID>, GlobalValue*>
98 GlobalRefsType GlobalRefs;
101 // If we could not resolve some functions at function compilation time
102 // (calls to functions before they are defined), resolve them now... Types
103 // are resolved when the constant pool has been completely parsed.
105 ResolveDefinitions(LateResolveValues);
107 // Check to make sure that all global value forward references have been
110 if (!GlobalRefs.empty()) {
111 std::string UndefinedReferences = "Unresolved global references exist:\n";
113 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
115 UndefinedReferences += " " + I->first.first->getDescription() + " " +
116 I->first.second.getName() + "\n";
118 error(UndefinedReferences);
122 if (CurrentModule->getDataLayout().empty()) {
123 std::string dataLayout;
124 if (Endian != Module::AnyEndianness)
125 dataLayout.append(Endian == Module::BigEndian ? "E" : "e");
126 if (PointerSize != Module::AnyPointerSize) {
127 if (!dataLayout.empty())
129 dataLayout.append(PointerSize == Module::Pointer64 ?
130 "p:64:64" : "p:32:32");
132 CurrentModule->setDataLayout(dataLayout);
135 Values.clear(); // Clear out function local definitions
140 // GetForwardRefForGlobal - Check to see if there is a forward reference
141 // for this global. If so, remove it from the GlobalRefs map and return it.
142 // If not, just return null.
143 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
144 // Check to see if there is a forward reference to this global variable...
145 // if there is, eliminate it and patch the reference to use the new def'n.
146 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
147 GlobalValue *Ret = 0;
148 if (I != GlobalRefs.end()) {
154 void setEndianness(Module::Endianness E) { Endian = E; }
155 void setPointerSize(Module::PointerSize sz) { PointerSize = sz; }
158 Module::Endianness PerModuleInfo::Endian = Module::AnyEndianness;
159 Module::PointerSize PerModuleInfo::PointerSize = Module::AnyPointerSize;
161 static struct PerFunctionInfo {
162 Function *CurrentFunction; // Pointer to current function being created
164 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
165 std::map<const Type*, ValueList> LateResolveValues;
166 bool isDeclare; // Is this function a forward declararation?
167 GlobalValue::LinkageTypes Linkage;// Linkage for forward declaration.
169 /// BBForwardRefs - When we see forward references to basic blocks, keep
170 /// track of them here.
171 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
172 std::vector<BasicBlock*> NumberedBlocks;
173 RenameMapType RenameMap;
176 inline PerFunctionInfo() {
179 Linkage = GlobalValue::ExternalLinkage;
182 inline void FunctionStart(Function *M) {
187 void FunctionDone() {
188 NumberedBlocks.clear();
190 // Any forward referenced blocks left?
191 if (!BBForwardRefs.empty()) {
192 error("Undefined reference to label " +
193 BBForwardRefs.begin()->first->getName());
197 // Resolve all forward references now.
198 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
200 Values.clear(); // Clear out function local definitions
204 Linkage = GlobalValue::ExternalLinkage;
206 } CurFun; // Info for the current function...
208 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
211 //===----------------------------------------------------------------------===//
212 // Code to handle definitions of all the types
213 //===----------------------------------------------------------------------===//
215 static int InsertValue(Value *V,
216 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
217 if (V->hasName()) return -1; // Is this a numbered definition?
219 // Yes, insert the value into the value table...
220 ValueList &List = ValueTab[V->getType()];
222 return List.size()-1;
225 static const Type *getType(const ValID &D, bool DoNotImprovise = false) {
227 case ValID::NumberVal: // Is it a numbered definition?
228 // Module constants occupy the lowest numbered slots...
229 if ((unsigned)D.Num < CurModule.Types.size()) {
230 return CurModule.Types[(unsigned)D.Num];
233 case ValID::NameVal: // Is it a named definition?
234 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
235 D.destroy(); // Free old strdup'd memory...
240 error("Internal parser error: Invalid symbol type reference");
244 // If we reached here, we referenced either a symbol that we don't know about
245 // or an id number that hasn't been read yet. We may be referencing something
246 // forward, so just create an entry to be resolved later and get to it...
248 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
251 if (inFunctionScope()) {
252 if (D.Type == ValID::NameVal) {
253 error("Reference to an undefined type: '" + D.getName() + "'");
256 error("Reference to an undefined type: #" + itostr(D.Num));
261 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
262 if (I != CurModule.LateResolveTypes.end())
265 Type *Typ = OpaqueType::get();
266 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
270 // getExistingValue - Look up the value specified by the provided type and
271 // the provided ValID. If the value exists and has already been defined, return
272 // it. Otherwise return null.
274 static Value *getExistingValue(const Type *Ty, const ValID &D) {
275 if (isa<FunctionType>(Ty)) {
276 error("Functions are not values and must be referenced as pointers");
280 case ValID::NumberVal: { // Is it a numbered definition?
281 unsigned Num = (unsigned)D.Num;
283 // Module constants occupy the lowest numbered slots...
284 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
285 if (VI != CurModule.Values.end()) {
286 if (Num < VI->second.size())
287 return VI->second[Num];
288 Num -= VI->second.size();
291 // Make sure that our type is within bounds
292 VI = CurFun.Values.find(Ty);
293 if (VI == CurFun.Values.end()) return 0;
295 // Check that the number is within bounds...
296 if (VI->second.size() <= Num) return 0;
298 return VI->second[Num];
301 case ValID::NameVal: { // Is it a named definition?
302 // Get the name out of the ID
303 std::string Name(D.Name);
305 RenameMapKey Key = std::make_pair(Name, Ty);
306 if (inFunctionScope()) {
307 // See if the name was renamed
308 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
309 std::string LookupName;
310 if (I != CurFun.RenameMap.end())
311 LookupName = I->second;
314 SymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
315 V = SymTab.lookup(Ty, LookupName);
318 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
319 std::string LookupName;
320 if (I != CurModule.RenameMap.end())
321 LookupName = I->second;
324 V = CurModule.CurrentModule->getValueSymbolTable().lookup(Ty, LookupName);
329 D.destroy(); // Free old strdup'd memory...
333 // Check to make sure that "Ty" is an integral type, and that our
334 // value will fit into the specified type...
335 case ValID::ConstSIntVal: // Is it a constant pool reference??
336 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
337 error("Signed integral constant '" + itostr(D.ConstPool64) +
338 "' is invalid for type '" + Ty->getDescription() + "'");
340 return ConstantInt::get(Ty, D.ConstPool64);
342 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
343 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
344 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
345 error("Integral constant '" + utostr(D.UConstPool64) +
346 "' is invalid or out of range");
347 else // This is really a signed reference. Transmogrify.
348 return ConstantInt::get(Ty, D.ConstPool64);
350 return ConstantInt::get(Ty, D.UConstPool64);
352 case ValID::ConstFPVal: // Is it a floating point const pool reference?
353 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
354 error("FP constant invalid for type");
355 return ConstantFP::get(Ty, D.ConstPoolFP);
357 case ValID::ConstNullVal: // Is it a null value?
358 if (!isa<PointerType>(Ty))
359 error("Cannot create a a non pointer null");
360 return ConstantPointerNull::get(cast<PointerType>(Ty));
362 case ValID::ConstUndefVal: // Is it an undef value?
363 return UndefValue::get(Ty);
365 case ValID::ConstZeroVal: // Is it a zero value?
366 return Constant::getNullValue(Ty);
368 case ValID::ConstantVal: // Fully resolved constant?
369 if (D.ConstantValue->getType() != Ty)
370 error("Constant expression type different from required type");
371 return D.ConstantValue;
373 case ValID::InlineAsmVal: { // Inline asm expression
374 const PointerType *PTy = dyn_cast<PointerType>(Ty);
375 const FunctionType *FTy =
376 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
377 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
378 error("Invalid type for asm constraint string");
379 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
380 D.IAD->HasSideEffects);
381 D.destroy(); // Free InlineAsmDescriptor.
385 assert(0 && "Unhandled case");
389 assert(0 && "Unhandled case");
393 // getVal - This function is identical to getExistingValue, except that if a
394 // value is not already defined, it "improvises" by creating a placeholder var
395 // that looks and acts just like the requested variable. When the value is
396 // defined later, all uses of the placeholder variable are replaced with the
399 static Value *getVal(const Type *Ty, const ValID &ID) {
400 if (Ty == Type::LabelTy)
401 error("Cannot use a basic block here");
403 // See if the value has already been defined.
404 Value *V = getExistingValue(Ty, ID);
407 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
408 error("Invalid use of a composite type");
410 // If we reached here, we referenced either a symbol that we don't know about
411 // or an id number that hasn't been read yet. We may be referencing something
412 // forward, so just create an entry to be resolved later and get to it...
413 V = new Argument(Ty);
415 // Remember where this forward reference came from. FIXME, shouldn't we try
416 // to recycle these things??
417 CurModule.PlaceHolderInfo.insert(
418 std::make_pair(V, std::make_pair(ID, Upgradelineno-1)));
420 if (inFunctionScope())
421 InsertValue(V, CurFun.LateResolveValues);
423 InsertValue(V, CurModule.LateResolveValues);
427 /// getBBVal - This is used for two purposes:
428 /// * If isDefinition is true, a new basic block with the specified ID is being
430 /// * If isDefinition is true, this is a reference to a basic block, which may
431 /// or may not be a forward reference.
433 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
434 assert(inFunctionScope() && "Can't get basic block at global scope");
440 error("Illegal label reference " + ID.getName());
442 case ValID::NumberVal: // Is it a numbered definition?
443 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
444 CurFun.NumberedBlocks.resize(ID.Num+1);
445 BB = CurFun.NumberedBlocks[ID.Num];
447 case ValID::NameVal: // Is it a named definition?
449 if (Value *N = CurFun.CurrentFunction->
450 getValueSymbolTable().lookup(Type::LabelTy, Name)) {
451 if (N->getType() != Type::LabelTy)
452 error("Name '" + Name + "' does not refer to a BasicBlock");
453 BB = cast<BasicBlock>(N);
458 // See if the block has already been defined.
460 // If this is the definition of the block, make sure the existing value was
461 // just a forward reference. If it was a forward reference, there will be
462 // an entry for it in the PlaceHolderInfo map.
463 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
464 // The existing value was a definition, not a forward reference.
465 error("Redefinition of label " + ID.getName());
467 ID.destroy(); // Free strdup'd memory.
471 // Otherwise this block has not been seen before.
472 BB = new BasicBlock("", CurFun.CurrentFunction);
473 if (ID.Type == ValID::NameVal) {
474 BB->setName(ID.Name);
476 CurFun.NumberedBlocks[ID.Num] = BB;
479 // If this is not a definition, keep track of it so we can use it as a forward
482 // Remember where this forward reference came from.
483 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
485 // The forward declaration could have been inserted anywhere in the
486 // function: insert it into the correct place now.
487 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
488 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
495 //===----------------------------------------------------------------------===//
496 // Code to handle forward references in instructions
497 //===----------------------------------------------------------------------===//
499 // This code handles the late binding needed with statements that reference
500 // values not defined yet... for example, a forward branch, or the PHI node for
503 // This keeps a table (CurFun.LateResolveValues) of all such forward references
504 // and back patchs after we are done.
507 // ResolveDefinitions - If we could not resolve some defs at parsing
508 // time (forward branches, phi functions for loops, etc...) resolve the
512 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
513 std::map<const Type*,ValueList> *FutureLateResolvers) {
514 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
515 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
516 E = LateResolvers.end(); LRI != E; ++LRI) {
517 ValueList &List = LRI->second;
518 while (!List.empty()) {
519 Value *V = List.back();
522 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
523 CurModule.PlaceHolderInfo.find(V);
524 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
526 ValID &DID = PHI->second.first;
528 Value *TheRealValue = getExistingValue(LRI->first, DID);
530 V->replaceAllUsesWith(TheRealValue);
532 CurModule.PlaceHolderInfo.erase(PHI);
533 } else if (FutureLateResolvers) {
534 // Functions have their unresolved items forwarded to the module late
536 InsertValue(V, *FutureLateResolvers);
538 if (DID.Type == ValID::NameVal) {
539 error("Reference to an invalid definition: '" +DID.getName()+
540 "' of type '" + V->getType()->getDescription() + "'",
544 error("Reference to an invalid definition: #" +
545 itostr(DID.Num) + " of type '" +
546 V->getType()->getDescription() + "'", PHI->second.second);
553 LateResolvers.clear();
556 // ResolveTypeTo - A brand new type was just declared. This means that (if
557 // name is not null) things referencing Name can be resolved. Otherwise, things
558 // refering to the number can be resolved. Do this now.
560 static void ResolveTypeTo(char *Name, const Type *ToTy) {
562 if (Name) D = ValID::create(Name);
563 else D = ValID::create((int)CurModule.Types.size());
565 std::map<ValID, PATypeHolder>::iterator I =
566 CurModule.LateResolveTypes.find(D);
567 if (I != CurModule.LateResolveTypes.end()) {
568 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
569 CurModule.LateResolveTypes.erase(I);
573 static std::string makeNameUnique(const std::string& Name) {
574 static unsigned UniqueNameCounter = 1;
575 std::string Result(Name);
576 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
580 // setValueName - Set the specified value to the name given. The name may be
581 // null potentially, in which case this is a noop. The string passed in is
582 // assumed to be a malloc'd string buffer, and is free'd by this function.
584 static void setValueName(Value *V, char *NameStr) {
586 std::string Name(NameStr); // Copy string
587 free(NameStr); // Free old string
589 if (V->getType() == Type::VoidTy) {
590 error("Can't assign name '" + Name + "' to value with void type");
594 assert(inFunctionScope() && "Must be in function scope");
596 // Search the function's symbol table for an existing value of this name
598 SymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
599 SymbolTable::plane_const_iterator PI = ST.plane_begin(), PE =ST.plane_end();
600 for ( ; PI != PE; ++PI) {
601 SymbolTable::value_const_iterator VI = PI->second.find(Name);
602 if (VI != PI->second.end()) {
603 Existing = VI->second;
608 if (Existing->getType() == V->getType()) {
609 // The type of the Existing value and the new one are the same. This
610 // is probably a type plane collapsing error. If the types involved
611 // are both integer, just rename it. Otherwise it
612 // is a redefinition error.
613 if (!Existing->getType()->isInteger()) {
614 error("Redefinition of value named '" + Name + "' in the '" +
615 V->getType()->getDescription() + "' type plane");
619 // In LLVM 2.0 we don't allow names to be re-used for any values in a
620 // function, regardless of Type. Previously re-use of names was okay as
621 // long as they were distinct types. With type planes collapsing because
622 // of the signedness change and because of PR411, this can no longer be
623 // supported. We must search the entire symbol table for a conflicting
624 // name and make the name unique. No warning is needed as this can't
626 std::string NewName = makeNameUnique(Name);
627 // We're changing the name but it will probably be used by other
628 // instructions as operands later on. Consequently we have to retain
629 // a mapping of the renaming that we're doing.
630 RenameMapKey Key = std::make_pair(Name,V->getType());
631 CurFun.RenameMap[Key] = NewName;
640 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
641 /// this is a declaration, otherwise it is a definition.
642 static GlobalVariable *
643 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
644 bool isConstantGlobal, const Type *Ty,
645 Constant *Initializer) {
646 if (isa<FunctionType>(Ty))
647 error("Cannot declare global vars of function type");
649 const PointerType *PTy = PointerType::get(Ty);
653 Name = NameStr; // Copy string
654 free(NameStr); // Free old string
657 // See if this global value was forward referenced. If so, recycle the
661 ID = ValID::create((char*)Name.c_str());
663 ID = ValID::create((int)CurModule.Values[PTy].size());
666 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
667 // Move the global to the end of the list, from whereever it was
668 // previously inserted.
669 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
670 CurModule.CurrentModule->getGlobalList().remove(GV);
671 CurModule.CurrentModule->getGlobalList().push_back(GV);
672 GV->setInitializer(Initializer);
673 GV->setLinkage(Linkage);
674 GV->setConstant(isConstantGlobal);
675 InsertValue(GV, CurModule.Values);
679 // If this global has a name, check to see if there is already a definition
680 // of this global in the module and emit warnings if there are conflicts.
682 // The global has a name. See if there's an existing one of the same name.
683 if (CurModule.CurrentModule->getNamedGlobal(Name)) {
684 // We found an existing global ov the same name. This isn't allowed
685 // in LLVM 2.0. Consequently, we must alter the name of the global so it
686 // can at least compile. This can happen because of type planes
687 // There is alread a global of the same name which means there is a
688 // conflict. Let's see what we can do about it.
689 std::string NewName(makeNameUnique(Name));
690 if (Linkage == GlobalValue::InternalLinkage) {
691 // The linkage type is internal so just warn about the rename without
692 // invoking "scarey language" about linkage failures. GVars with
693 // InternalLinkage can be renamed at will.
694 warning("Global variable '" + Name + "' was renamed to '"+
697 // The linkage of this gval is external so we can't reliably rename
698 // it because it could potentially create a linking problem.
699 // However, we can't leave the name conflict in the output either or
700 // it won't assemble with LLVM 2.0. So, all we can do is rename
701 // this one to something unique and emit a warning about the problem.
702 warning("Renaming global variable '" + Name + "' to '" + NewName +
703 "' may cause linkage errors");
706 // Put the renaming in the global rename map
707 RenameMapKey Key = std::make_pair(Name,PointerType::get(Ty));
708 CurModule.RenameMap[Key] = NewName;
715 // Otherwise there is no existing GV to use, create one now.
717 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
718 CurModule.CurrentModule);
719 InsertValue(GV, CurModule.Values);
723 // setTypeName - Set the specified type to the name given. The name may be
724 // null potentially, in which case this is a noop. The string passed in is
725 // assumed to be a malloc'd string buffer, and is freed by this function.
727 // This function returns true if the type has already been defined, but is
728 // allowed to be redefined in the specified context. If the name is a new name
729 // for the type plane, it is inserted and false is returned.
730 static bool setTypeName(const Type *T, char *NameStr) {
731 assert(!inFunctionScope() && "Can't give types function-local names");
732 if (NameStr == 0) return false;
734 std::string Name(NameStr); // Copy string
735 free(NameStr); // Free old string
737 // We don't allow assigning names to void type
738 if (T == Type::VoidTy) {
739 error("Can't assign name '" + Name + "' to the void type");
743 // Set the type name, checking for conflicts as we do so.
744 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
746 if (AlreadyExists) { // Inserting a name that is already defined???
747 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
748 assert(Existing && "Conflict but no matching type?");
750 // There is only one case where this is allowed: when we are refining an
751 // opaque type. In this case, Existing will be an opaque type.
752 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
753 // We ARE replacing an opaque type!
754 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
758 // Otherwise, this is an attempt to redefine a type. That's okay if
759 // the redefinition is identical to the original. This will be so if
760 // Existing and T point to the same Type object. In this one case we
761 // allow the equivalent redefinition.
762 if (Existing == T) return true; // Yes, it's equal.
764 // Any other kind of (non-equivalent) redefinition is an error.
765 error("Redefinition of type named '" + Name + "' in the '" +
766 T->getDescription() + "' type plane");
772 //===----------------------------------------------------------------------===//
773 // Code for handling upreferences in type names...
776 // TypeContains - Returns true if Ty directly contains E in it.
778 static bool TypeContains(const Type *Ty, const Type *E) {
779 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
780 E) != Ty->subtype_end();
785 // NestingLevel - The number of nesting levels that need to be popped before
786 // this type is resolved.
787 unsigned NestingLevel;
789 // LastContainedTy - This is the type at the current binding level for the
790 // type. Every time we reduce the nesting level, this gets updated.
791 const Type *LastContainedTy;
793 // UpRefTy - This is the actual opaque type that the upreference is
797 UpRefRecord(unsigned NL, OpaqueType *URTy)
798 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
802 // UpRefs - A list of the outstanding upreferences that need to be resolved.
803 static std::vector<UpRefRecord> UpRefs;
805 /// HandleUpRefs - Every time we finish a new layer of types, this function is
806 /// called. It loops through the UpRefs vector, which is a list of the
807 /// currently active types. For each type, if the up reference is contained in
808 /// the newly completed type, we decrement the level count. When the level
809 /// count reaches zero, the upreferenced type is the type that is passed in:
810 /// thus we can complete the cycle.
812 static PATypeHolder HandleUpRefs(const Type *ty) {
813 // If Ty isn't abstract, or if there are no up-references in it, then there is
814 // nothing to resolve here.
815 if (!ty->isAbstract() || UpRefs.empty()) return ty;
818 UR_OUT("Type '" << Ty->getDescription() <<
819 "' newly formed. Resolving upreferences.\n" <<
820 UpRefs.size() << " upreferences active!\n");
822 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
823 // to zero), we resolve them all together before we resolve them to Ty. At
824 // the end of the loop, if there is anything to resolve to Ty, it will be in
826 OpaqueType *TypeToResolve = 0;
828 for (unsigned i = 0; i != UpRefs.size(); ++i) {
829 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
830 << UpRefs[i].second->getDescription() << ") = "
831 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
832 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
833 // Decrement level of upreference
834 unsigned Level = --UpRefs[i].NestingLevel;
835 UpRefs[i].LastContainedTy = Ty;
836 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
837 if (Level == 0) { // Upreference should be resolved!
838 if (!TypeToResolve) {
839 TypeToResolve = UpRefs[i].UpRefTy;
841 UR_OUT(" * Resolving upreference for "
842 << UpRefs[i].second->getDescription() << "\n";
843 std::string OldName = UpRefs[i].UpRefTy->getDescription());
844 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
845 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
846 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
848 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
849 --i; // Do not skip the next element...
855 UR_OUT(" * Resolving upreference for "
856 << UpRefs[i].second->getDescription() << "\n";
857 std::string OldName = TypeToResolve->getDescription());
858 TypeToResolve->refineAbstractTypeTo(Ty);
864 static inline Instruction::TermOps
865 getTermOp(TermOps op) {
867 default : assert(0 && "Invalid OldTermOp");
868 case RetOp : return Instruction::Ret;
869 case BrOp : return Instruction::Br;
870 case SwitchOp : return Instruction::Switch;
871 case InvokeOp : return Instruction::Invoke;
872 case UnwindOp : return Instruction::Unwind;
873 case UnreachableOp: return Instruction::Unreachable;
877 static inline Instruction::BinaryOps
878 getBinaryOp(BinaryOps op, const Type *Ty, Signedness Sign) {
880 default : assert(0 && "Invalid OldBinaryOps");
886 case SetGT : assert(0 && "Should use getCompareOp");
887 case AddOp : return Instruction::Add;
888 case SubOp : return Instruction::Sub;
889 case MulOp : return Instruction::Mul;
891 // This is an obsolete instruction so we must upgrade it based on the
892 // types of its operands.
893 bool isFP = Ty->isFloatingPoint();
894 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
895 // If its a packed type we want to use the element type
896 isFP = PTy->getElementType()->isFloatingPoint();
898 return Instruction::FDiv;
899 else if (Sign == Signed)
900 return Instruction::SDiv;
901 return Instruction::UDiv;
903 case UDivOp : return Instruction::UDiv;
904 case SDivOp : return Instruction::SDiv;
905 case FDivOp : return Instruction::FDiv;
907 // This is an obsolete instruction so we must upgrade it based on the
908 // types of its operands.
909 bool isFP = Ty->isFloatingPoint();
910 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
911 // If its a packed type we want to use the element type
912 isFP = PTy->getElementType()->isFloatingPoint();
913 // Select correct opcode
915 return Instruction::FRem;
916 else if (Sign == Signed)
917 return Instruction::SRem;
918 return Instruction::URem;
920 case URemOp : return Instruction::URem;
921 case SRemOp : return Instruction::SRem;
922 case FRemOp : return Instruction::FRem;
923 case AndOp : return Instruction::And;
924 case OrOp : return Instruction::Or;
925 case XorOp : return Instruction::Xor;
929 static inline Instruction::OtherOps
930 getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
932 bool isSigned = Sign == Signed;
933 bool isFP = Ty->isFloatingPoint();
935 default : assert(0 && "Invalid OldSetCC");
938 predicate = FCmpInst::FCMP_OEQ;
939 return Instruction::FCmp;
941 predicate = ICmpInst::ICMP_EQ;
942 return Instruction::ICmp;
946 predicate = FCmpInst::FCMP_UNE;
947 return Instruction::FCmp;
949 predicate = ICmpInst::ICMP_NE;
950 return Instruction::ICmp;
954 predicate = FCmpInst::FCMP_OLE;
955 return Instruction::FCmp;
958 predicate = ICmpInst::ICMP_SLE;
960 predicate = ICmpInst::ICMP_ULE;
961 return Instruction::ICmp;
965 predicate = FCmpInst::FCMP_OGE;
966 return Instruction::FCmp;
969 predicate = ICmpInst::ICMP_SGE;
971 predicate = ICmpInst::ICMP_UGE;
972 return Instruction::ICmp;
976 predicate = FCmpInst::FCMP_OLT;
977 return Instruction::FCmp;
980 predicate = ICmpInst::ICMP_SLT;
982 predicate = ICmpInst::ICMP_ULT;
983 return Instruction::ICmp;
987 predicate = FCmpInst::FCMP_OGT;
988 return Instruction::FCmp;
991 predicate = ICmpInst::ICMP_SGT;
993 predicate = ICmpInst::ICMP_UGT;
994 return Instruction::ICmp;
999 static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1001 default : assert(0 && "Invalid OldMemoryOps");
1002 case MallocOp : return Instruction::Malloc;
1003 case FreeOp : return Instruction::Free;
1004 case AllocaOp : return Instruction::Alloca;
1005 case LoadOp : return Instruction::Load;
1006 case StoreOp : return Instruction::Store;
1007 case GetElementPtrOp : return Instruction::GetElementPtr;
1011 static inline Instruction::OtherOps
1012 getOtherOp(OtherOps op, Signedness Sign) {
1014 default : assert(0 && "Invalid OldOtherOps");
1015 case PHIOp : return Instruction::PHI;
1016 case CallOp : return Instruction::Call;
1017 case ShlOp : return Instruction::Shl;
1020 return Instruction::AShr;
1021 return Instruction::LShr;
1022 case SelectOp : return Instruction::Select;
1023 case UserOp1 : return Instruction::UserOp1;
1024 case UserOp2 : return Instruction::UserOp2;
1025 case VAArg : return Instruction::VAArg;
1026 case ExtractElementOp : return Instruction::ExtractElement;
1027 case InsertElementOp : return Instruction::InsertElement;
1028 case ShuffleVectorOp : return Instruction::ShuffleVector;
1029 case ICmpOp : return Instruction::ICmp;
1030 case FCmpOp : return Instruction::FCmp;
1031 case LShrOp : return Instruction::LShr;
1032 case AShrOp : return Instruction::AShr;
1036 static inline Value*
1037 getCast(CastOps op, Value *Src, Signedness SrcSign, const Type *DstTy,
1038 Signedness DstSign, bool ForceInstruction = false) {
1039 Instruction::CastOps Opcode;
1040 const Type* SrcTy = Src->getType();
1042 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1043 // fp -> ptr cast is no longer supported but we must upgrade this
1044 // by doing a double cast: fp -> int -> ptr
1045 SrcTy = Type::Int64Ty;
1046 Opcode = Instruction::IntToPtr;
1047 if (isa<Constant>(Src)) {
1048 Src = ConstantExpr::getCast(Instruction::FPToUI,
1049 cast<Constant>(Src), SrcTy);
1051 std::string NewName(makeNameUnique(Src->getName()));
1052 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1054 } else if (isa<IntegerType>(DstTy) &&
1055 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1056 // cast type %x to bool was previously defined as setne type %x, null
1057 // The cast semantic is now to truncate, not compare so we must retain
1058 // the original intent by replacing the cast with a setne
1059 Constant* Null = Constant::getNullValue(SrcTy);
1060 Instruction::OtherOps Opcode = Instruction::ICmp;
1061 unsigned short predicate = ICmpInst::ICMP_NE;
1062 if (SrcTy->isFloatingPoint()) {
1063 Opcode = Instruction::FCmp;
1064 predicate = FCmpInst::FCMP_ONE;
1065 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1066 error("Invalid cast to bool");
1068 if (isa<Constant>(Src) && !ForceInstruction)
1069 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1071 return CmpInst::create(Opcode, predicate, Src, Null);
1073 // Determine the opcode to use by calling CastInst::getCastOpcode
1075 CastInst::getCastOpcode(Src, SrcSign == Signed, DstTy, DstSign == Signed);
1077 } else switch (op) {
1078 default: assert(0 && "Invalid cast token");
1079 case TruncOp: Opcode = Instruction::Trunc; break;
1080 case ZExtOp: Opcode = Instruction::ZExt; break;
1081 case SExtOp: Opcode = Instruction::SExt; break;
1082 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1083 case FPExtOp: Opcode = Instruction::FPExt; break;
1084 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1085 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1086 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1087 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1088 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1089 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1090 case BitCastOp: Opcode = Instruction::BitCast; break;
1093 if (isa<Constant>(Src) && !ForceInstruction)
1094 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1095 return CastInst::create(Opcode, Src, DstTy);
1098 static Instruction *
1099 upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1100 std::vector<Value*>& Args) {
1102 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1103 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1104 if (Args.size() != 2)
1105 error("Invalid prototype for " + Name + " prototype");
1106 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1108 static unsigned upgradeCount = 1;
1109 const Type* PtrTy = PointerType::get(Type::Int8Ty);
1110 std::vector<const Type*> Params;
1111 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1112 if (Args.size() != 1)
1113 error("Invalid prototype for " + Name + " prototype");
1114 Params.push_back(PtrTy);
1115 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1116 const PointerType *PFTy = PointerType::get(FTy);
1117 Value* Func = getVal(PFTy, ID);
1118 std::string InstName("va_upgrade");
1119 InstName += llvm::utostr(upgradeCount++);
1120 Args[0] = new BitCastInst(Args[0], PtrTy, InstName, CurBB);
1121 return new CallInst(Func, Args);
1122 } else if (Name == "llvm.va_copy") {
1123 if (Args.size() != 2)
1124 error("Invalid prototype for " + Name + " prototype");
1125 Params.push_back(PtrTy);
1126 Params.push_back(PtrTy);
1127 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1128 const PointerType *PFTy = PointerType::get(FTy);
1129 Value* Func = getVal(PFTy, ID);
1130 std::string InstName0("va_upgrade");
1131 InstName0 += llvm::utostr(upgradeCount++);
1132 std::string InstName1("va_upgrade");
1133 InstName1 += llvm::utostr(upgradeCount++);
1134 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1135 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1136 return new CallInst(Func, Args);
1142 const Type* upgradeGEPIndices(const Type* PTy,
1143 std::vector<ValueInfo> *Indices,
1144 std::vector<Value*> &VIndices,
1145 std::vector<Constant*> *CIndices = 0) {
1146 // Traverse the indices with a gep_type_iterator so we can build the list
1147 // of constant and value indices for use later. Also perform upgrades
1149 if (CIndices) CIndices->clear();
1150 for (unsigned i = 0, e = Indices->size(); i != e; ++i)
1151 VIndices.push_back((*Indices)[i].V);
1152 generic_gep_type_iterator<std::vector<Value*>::iterator>
1153 GTI = gep_type_begin(PTy, VIndices.begin(), VIndices.end()),
1154 GTE = gep_type_end(PTy, VIndices.begin(), VIndices.end());
1155 for (unsigned i = 0, e = Indices->size(); i != e && GTI != GTE; ++i, ++GTI) {
1156 Value *Index = VIndices[i];
1157 if (CIndices && !isa<Constant>(Index))
1158 error("Indices to constant getelementptr must be constants");
1159 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1160 // struct indices to i32 struct indices with ZExt for compatibility.
1161 else if (isa<StructType>(*GTI)) { // Only change struct indices
1162 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Index))
1163 if (CUI->getType()->getBitWidth() == 8)
1165 ConstantExpr::getCast(Instruction::ZExt, CUI, Type::Int32Ty);
1167 // Make sure that unsigned SequentialType indices are zext'd to
1168 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1169 // all indices for SequentialType elements. We must retain the same
1170 // semantic (zext) for unsigned types.
1171 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType()))
1172 if (Ity->getBitWidth() < 64 && (*Indices)[i].S == Unsigned) {
1174 Index = ConstantExpr::getCast(Instruction::ZExt,
1175 cast<Constant>(Index), Type::Int64Ty);
1177 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1178 makeNameUnique("gep_upgrade"), CurBB);
1179 VIndices[i] = Index;
1182 // Add to the CIndices list, if requested.
1184 CIndices->push_back(cast<Constant>(Index));
1188 GetElementPtrInst::getIndexedType(PTy, VIndices, true);
1190 error("Index list invalid for constant getelementptr");
1194 Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1195 bool debug, bool addAttrs)
1198 CurFilename = infile;
1201 AddAttributes = addAttrs;
1202 ObsoleteVarArgs = false;
1205 CurModule.CurrentModule = new Module(CurFilename);
1207 // Check to make sure the parser succeeded
1210 delete ParserResult;
1211 std::cerr << "llvm-upgrade: parse failed.\n";
1215 // Check to make sure that parsing produced a result
1216 if (!ParserResult) {
1217 std::cerr << "llvm-upgrade: no parse result.\n";
1221 // Reset ParserResult variable while saving its value for the result.
1222 Module *Result = ParserResult;
1225 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1228 if ((F = Result->getNamedFunction("llvm.va_start"))
1229 && F->getFunctionType()->getNumParams() == 0)
1230 ObsoleteVarArgs = true;
1231 if((F = Result->getNamedFunction("llvm.va_copy"))
1232 && F->getFunctionType()->getNumParams() == 1)
1233 ObsoleteVarArgs = true;
1236 if (ObsoleteVarArgs && NewVarArgs) {
1237 error("This file is corrupt: it uses both new and old style varargs");
1241 if(ObsoleteVarArgs) {
1242 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
1243 if (F->arg_size() != 0) {
1244 error("Obsolete va_start takes 0 argument");
1250 //bar = alloca typeof(foo)
1254 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1255 const Type* ArgTy = F->getFunctionType()->getReturnType();
1256 const Type* ArgTyPtr = PointerType::get(ArgTy);
1257 Function* NF = cast<Function>(Result->getOrInsertFunction(
1258 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1260 while (!F->use_empty()) {
1261 CallInst* CI = cast<CallInst>(F->use_back());
1262 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1263 new CallInst(NF, bar, "", CI);
1264 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1265 CI->replaceAllUsesWith(foo);
1266 CI->getParent()->getInstList().erase(CI);
1268 Result->getFunctionList().erase(F);
1271 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
1272 if(F->arg_size() != 1) {
1273 error("Obsolete va_end takes 1 argument");
1279 //bar = alloca 1 of typeof(foo)
1281 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1282 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1283 const Type* ArgTyPtr = PointerType::get(ArgTy);
1284 Function* NF = cast<Function>(Result->getOrInsertFunction(
1285 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1287 while (!F->use_empty()) {
1288 CallInst* CI = cast<CallInst>(F->use_back());
1289 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1290 new StoreInst(CI->getOperand(1), bar, CI);
1291 new CallInst(NF, bar, "", CI);
1292 CI->getParent()->getInstList().erase(CI);
1294 Result->getFunctionList().erase(F);
1297 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
1298 if(F->arg_size() != 1) {
1299 error("Obsolete va_copy takes 1 argument");
1304 //a = alloca 1 of typeof(foo)
1305 //b = alloca 1 of typeof(foo)
1310 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1311 const Type* ArgTy = F->getFunctionType()->getReturnType();
1312 const Type* ArgTyPtr = PointerType::get(ArgTy);
1313 Function* NF = cast<Function>(Result->getOrInsertFunction(
1314 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1316 while (!F->use_empty()) {
1317 CallInst* CI = cast<CallInst>(F->use_back());
1318 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1319 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1320 new StoreInst(CI->getOperand(1), b, CI);
1321 new CallInst(NF, a, b, "", CI);
1322 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1323 CI->replaceAllUsesWith(foo);
1324 CI->getParent()->getInstList().erase(CI);
1326 Result->getFunctionList().erase(F);
1333 } // end llvm namespace
1335 using namespace llvm;
1340 llvm::Module *ModuleVal;
1341 llvm::Function *FunctionVal;
1342 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1343 llvm::BasicBlock *BasicBlockVal;
1344 llvm::TerminatorInst *TermInstVal;
1345 llvm::InstrInfo InstVal;
1346 llvm::ConstInfo ConstVal;
1347 llvm::ValueInfo ValueVal;
1348 llvm::PATypeInfo TypeVal;
1349 llvm::TypeInfo PrimType;
1350 llvm::PHIListInfo PHIList;
1351 std::list<llvm::PATypeInfo> *TypeList;
1352 std::vector<llvm::ValueInfo> *ValueList;
1353 std::vector<llvm::ConstInfo> *ConstVector;
1356 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1357 // Represent the RHS of PHI node
1358 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1360 llvm::GlobalValue::LinkageTypes Linkage;
1368 char *StrVal; // This memory is strdup'd!
1369 llvm::ValID ValIDVal; // strdup'd memory maybe!
1371 llvm::BinaryOps BinaryOpVal;
1372 llvm::TermOps TermOpVal;
1373 llvm::MemoryOps MemOpVal;
1374 llvm::OtherOps OtherOpVal;
1375 llvm::CastOps CastOpVal;
1376 llvm::ICmpInst::Predicate IPred;
1377 llvm::FCmpInst::Predicate FPred;
1378 llvm::Module::Endianness Endianness;
1381 %type <ModuleVal> Module FunctionList
1382 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1383 %type <BasicBlockVal> BasicBlock InstructionList
1384 %type <TermInstVal> BBTerminatorInst
1385 %type <InstVal> Inst InstVal MemoryInst
1386 %type <ConstVal> ConstVal ConstExpr
1387 %type <ConstVector> ConstVector
1388 %type <ArgList> ArgList ArgListH
1389 %type <ArgVal> ArgVal
1390 %type <PHIList> PHIList
1391 %type <ValueList> ValueRefList ValueRefListE // For call param lists
1392 %type <ValueList> IndexList // For GEP derived indices
1393 %type <TypeList> TypeListI ArgTypeListI
1394 %type <JumpTable> JumpTable
1395 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1396 %type <BoolVal> OptVolatile // 'volatile' or not
1397 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1398 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1399 %type <Linkage> OptLinkage
1400 %type <Endianness> BigOrLittle
1402 // ValueRef - Unresolved reference to a definition or BB
1403 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1404 %type <ValueVal> ResolvedVal // <type> <valref> pair
1406 // Tokens and types for handling constant integer values
1408 // ESINT64VAL - A negative number within long long range
1409 %token <SInt64Val> ESINT64VAL
1411 // EUINT64VAL - A positive number within uns. long long range
1412 %token <UInt64Val> EUINT64VAL
1413 %type <SInt64Val> EINT64VAL
1415 %token <SIntVal> SINTVAL // Signed 32 bit ints...
1416 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1417 %type <SIntVal> INTVAL
1418 %token <FPVal> FPVAL // Float or Double constant
1420 // Built in types...
1421 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
1422 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1423 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1424 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1426 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1427 %type <StrVal> Name OptName OptAssign
1428 %type <UIntVal> OptAlign OptCAlign
1429 %type <StrVal> OptSection SectionString
1431 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1432 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1433 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1434 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1435 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1436 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1437 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1438 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1440 %type <UIntVal> OptCallingConv
1442 // Basic Block Terminating Operators
1443 %token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1444 %token UNWIND EXCEPT
1447 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1448 %token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
1449 %token <BinaryOpVal> AND OR XOR
1450 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1451 %token <OtherOpVal> ICMP FCMP
1453 // Memory Instructions
1454 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1457 %type <OtherOpVal> ShiftOps
1458 %token <OtherOpVal> PHI_TOK SELECT SHL SHR ASHR LSHR VAARG
1459 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1460 %token VAARG_old VANEXT_old //OBSOLETE
1462 // Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
1463 %type <IPred> IPredicates
1464 %type <FPred> FPredicates
1465 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1466 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1468 %token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1469 %token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1470 %type <CastOpVal> CastOps
1476 // Handle constant integer size restriction and conversion...
1481 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1482 error("Value too large for type");
1488 : ESINT64VAL // These have same type and can't cause problems...
1490 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1491 error("Value too large for type");
1495 // Operations that are notably excluded from this list include:
1496 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1499 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1507 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1511 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1512 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1513 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1514 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1515 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1519 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1520 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1521 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1522 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1523 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1524 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1525 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1526 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1527 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1530 : SHL | SHR | ASHR | LSHR
1534 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1535 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1538 // These are some types that allow classification if we only want a particular
1539 // thing... for example, only a signed, unsigned, or integral type.
1541 : LONG | INT | SHORT | SBYTE
1545 : ULONG | UINT | USHORT | UBYTE
1549 : SIntType | UIntType
1556 // OptAssign - Value producing statements have an optional assignment component
1566 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1567 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1568 | WEAK { $$ = GlobalValue::WeakLinkage; }
1569 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1570 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1571 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1572 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1573 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1577 : /*empty*/ { $$ = CallingConv::C; }
1578 | CCC_TOK { $$ = CallingConv::C; }
1579 | CSRETCC_TOK { $$ = CallingConv::C; }
1580 | FASTCC_TOK { $$ = CallingConv::Fast; }
1581 | COLDCC_TOK { $$ = CallingConv::Cold; }
1582 | X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; }
1583 | X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; }
1584 | CC_TOK EUINT64VAL {
1585 if ((unsigned)$2 != $2)
1586 error("Calling conv too large");
1591 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1592 // a comma before it.
1594 : /*empty*/ { $$ = 0; }
1595 | ALIGN EUINT64VAL {
1597 if ($$ != 0 && !isPowerOf2_32($$))
1598 error("Alignment must be a power of two");
1603 : /*empty*/ { $$ = 0; }
1604 | ',' ALIGN EUINT64VAL {
1606 if ($$ != 0 && !isPowerOf2_32($$))
1607 error("Alignment must be a power of two");
1612 : SECTION STRINGCONSTANT {
1613 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1614 if ($2[i] == '"' || $2[i] == '\\')
1615 error("Invalid character in section name");
1621 : /*empty*/ { $$ = 0; }
1622 | SectionString { $$ = $1; }
1625 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1626 // is set to be the global we are processing.
1630 | ',' GlobalVarAttribute GlobalVarAttributes {}
1635 CurGV->setSection($1);
1638 | ALIGN EUINT64VAL {
1639 if ($2 != 0 && !isPowerOf2_32($2))
1640 error("Alignment must be a power of two");
1641 CurGV->setAlignment($2);
1646 //===----------------------------------------------------------------------===//
1647 // Types includes all predefined types... except void, because it can only be
1648 // used in specific contexts (function returning void for example). To have
1649 // access to it, a user must explicitly use TypesV.
1652 // TypesV includes all of 'Types', but it also includes the void type.
1656 $$.T = new PATypeHolder($1.T);
1664 $$.T = new PATypeHolder($1.T);
1671 if (!UpRefs.empty())
1672 error("Invalid upreference in type: " + (*$1.T)->getDescription());
1678 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
1679 | LONG | ULONG | FLOAT | DOUBLE | LABEL
1682 // Derived types are added later...
1685 $$.T = new PATypeHolder($1.T);
1689 $$.T = new PATypeHolder(OpaqueType::get());
1692 | SymbolicValueRef { // Named types are also simple types...
1693 const Type* tmp = getType($1);
1694 $$.T = new PATypeHolder(tmp);
1695 $$.S = Signless; // FIXME: what if its signed?
1697 | '\\' EUINT64VAL { // Type UpReference
1698 if ($2 > (uint64_t)~0U)
1699 error("Value out of range");
1700 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1701 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1702 $$.T = new PATypeHolder(OT);
1704 UR_OUT("New Upreference!\n");
1706 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1707 std::vector<const Type*> Params;
1708 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1709 E = $3->end(); I != E; ++I) {
1710 Params.push_back(I->T->get());
1713 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1714 if (isVarArg) Params.pop_back();
1716 $$.T = new PATypeHolder(HandleUpRefs(
1717 FunctionType::get($1.T->get(),Params,isVarArg)));
1719 delete $1.T; // Delete the return type handle
1720 delete $3; // Delete the argument list
1722 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1723 $$.T = new PATypeHolder(HandleUpRefs(ArrayType::get($4.T->get(),
1728 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1729 const llvm::Type* ElemTy = $4.T->get();
1730 if ((unsigned)$2 != $2)
1731 error("Unsigned result not equal to signed result");
1732 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
1733 error("Elements of a PackedType must be integer or floating point");
1734 if (!isPowerOf2_32($2))
1735 error("PackedType length should be a power of 2");
1736 $$.T = new PATypeHolder(HandleUpRefs(PackedType::get(ElemTy,
1741 | '{' TypeListI '}' { // Structure type?
1742 std::vector<const Type*> Elements;
1743 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
1744 E = $2->end(); I != E; ++I)
1745 Elements.push_back(I->T->get());
1746 $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1750 | '{' '}' { // Empty structure type?
1751 $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1754 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
1755 std::vector<const Type*> Elements;
1756 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1757 E = $3->end(); I != E; ++I) {
1758 Elements.push_back(I->T->get());
1761 $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1765 | '<' '{' '}' '>' { // Empty packed structure type?
1766 $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
1769 | UpRTypes '*' { // Pointer type?
1770 if ($1.T->get() == Type::LabelTy)
1771 error("Cannot form a pointer to a basic block");
1772 $$.T = new PATypeHolder(HandleUpRefs(PointerType::get($1.T->get())));
1778 // TypeList - Used for struct declarations and as a basis for function type
1779 // declaration type lists
1783 $$ = new std::list<PATypeInfo>();
1786 | TypeListI ',' UpRTypes {
1787 ($$=$1)->push_back($3);
1791 // ArgTypeList - List of types for a function type declaration...
1794 | TypeListI ',' DOTDOTDOT {
1796 VoidTI.T = new PATypeHolder(Type::VoidTy);
1797 VoidTI.S = Signless;
1798 ($$=$1)->push_back(VoidTI);
1801 $$ = new std::list<PATypeInfo>();
1803 VoidTI.T = new PATypeHolder(Type::VoidTy);
1804 VoidTI.S = Signless;
1805 $$->push_back(VoidTI);
1808 $$ = new std::list<PATypeInfo>();
1812 // ConstVal - The various declarations that go into the constant pool. This
1813 // production is used ONLY to represent constants that show up AFTER a 'const',
1814 // 'constant' or 'global' token at global scope. Constants that can be inlined
1815 // into other expressions (such as integers and constexprs) are handled by the
1816 // ResolvedVal, ValueRef and ConstValueRef productions.
1819 : Types '[' ConstVector ']' { // Nonempty unsized arr
1820 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1822 error("Cannot make array constant with type: '" +
1823 $1.T->get()->getDescription() + "'");
1824 const Type *ETy = ATy->getElementType();
1825 int NumElements = ATy->getNumElements();
1827 // Verify that we have the correct size...
1828 if (NumElements != -1 && NumElements != (int)$3->size())
1829 error("Type mismatch: constant sized array initialized with " +
1830 utostr($3->size()) + " arguments, but has size of " +
1831 itostr(NumElements) + "");
1833 // Verify all elements are correct type!
1834 std::vector<Constant*> Elems;
1835 for (unsigned i = 0; i < $3->size(); i++) {
1836 Constant *C = (*$3)[i].C;
1837 const Type* ValTy = C->getType();
1839 error("Element #" + utostr(i) + " is not of type '" +
1840 ETy->getDescription() +"' as required!\nIt is of type '"+
1841 ValTy->getDescription() + "'");
1844 $$.C = ConstantArray::get(ATy, Elems);
1850 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1852 error("Cannot make array constant with type: '" +
1853 $1.T->get()->getDescription() + "'");
1854 int NumElements = ATy->getNumElements();
1855 if (NumElements != -1 && NumElements != 0)
1856 error("Type mismatch: constant sized array initialized with 0"
1857 " arguments, but has size of " + itostr(NumElements) +"");
1858 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
1862 | Types 'c' STRINGCONSTANT {
1863 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1865 error("Cannot make array constant with type: '" +
1866 $1.T->get()->getDescription() + "'");
1867 int NumElements = ATy->getNumElements();
1868 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
1869 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
1870 error("String arrays require type i8, not '" + ETy->getDescription() +
1872 char *EndStr = UnEscapeLexed($3, true);
1873 if (NumElements != -1 && NumElements != (EndStr-$3))
1874 error("Can't build string constant of size " +
1875 itostr((int)(EndStr-$3)) + " when array has size " +
1876 itostr(NumElements) + "");
1877 std::vector<Constant*> Vals;
1878 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
1879 Vals.push_back(ConstantInt::get(ETy, *C));
1881 $$.C = ConstantArray::get(ATy, Vals);
1885 | Types '<' ConstVector '>' { // Nonempty unsized arr
1886 const PackedType *PTy = dyn_cast<PackedType>($1.T->get());
1888 error("Cannot make packed constant with type: '" +
1889 $1.T->get()->getDescription() + "'");
1890 const Type *ETy = PTy->getElementType();
1891 int NumElements = PTy->getNumElements();
1892 // Verify that we have the correct size...
1893 if (NumElements != -1 && NumElements != (int)$3->size())
1894 error("Type mismatch: constant sized packed initialized with " +
1895 utostr($3->size()) + " arguments, but has size of " +
1896 itostr(NumElements) + "");
1897 // Verify all elements are correct type!
1898 std::vector<Constant*> Elems;
1899 for (unsigned i = 0; i < $3->size(); i++) {
1900 Constant *C = (*$3)[i].C;
1901 const Type* ValTy = C->getType();
1903 error("Element #" + utostr(i) + " is not of type '" +
1904 ETy->getDescription() +"' as required!\nIt is of type '"+
1905 ValTy->getDescription() + "'");
1908 $$.C = ConstantPacked::get(PTy, Elems);
1913 | Types '{' ConstVector '}' {
1914 const StructType *STy = dyn_cast<StructType>($1.T->get());
1916 error("Cannot make struct constant with type: '" +
1917 $1.T->get()->getDescription() + "'");
1918 if ($3->size() != STy->getNumContainedTypes())
1919 error("Illegal number of initializers for structure type");
1921 // Check to ensure that constants are compatible with the type initializer!
1922 std::vector<Constant*> Fields;
1923 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
1924 Constant *C = (*$3)[i].C;
1925 if (C->getType() != STy->getElementType(i))
1926 error("Expected type '" + STy->getElementType(i)->getDescription() +
1927 "' for element #" + utostr(i) + " of structure initializer");
1928 Fields.push_back(C);
1930 $$.C = ConstantStruct::get(STy, Fields);
1936 const StructType *STy = dyn_cast<StructType>($1.T->get());
1938 error("Cannot make struct constant with type: '" +
1939 $1.T->get()->getDescription() + "'");
1940 if (STy->getNumContainedTypes() != 0)
1941 error("Illegal number of initializers for structure type");
1942 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
1946 | Types '<' '{' ConstVector '}' '>' {
1947 const StructType *STy = dyn_cast<StructType>($1.T->get());
1949 error("Cannot make packed struct constant with type: '" +
1950 $1.T->get()->getDescription() + "'");
1951 if ($4->size() != STy->getNumContainedTypes())
1952 error("Illegal number of initializers for packed structure type");
1954 // Check to ensure that constants are compatible with the type initializer!
1955 std::vector<Constant*> Fields;
1956 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
1957 Constant *C = (*$4)[i].C;
1958 if (C->getType() != STy->getElementType(i))
1959 error("Expected type '" + STy->getElementType(i)->getDescription() +
1960 "' for element #" + utostr(i) + " of packed struct initializer");
1961 Fields.push_back(C);
1963 $$.C = ConstantStruct::get(STy, Fields);
1968 | Types '<' '{' '}' '>' {
1969 const StructType *STy = dyn_cast<StructType>($1.T->get());
1971 error("Cannot make packed struct constant with type: '" +
1972 $1.T->get()->getDescription() + "'");
1973 if (STy->getNumContainedTypes() != 0)
1974 error("Illegal number of initializers for packed structure type");
1975 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
1980 const PointerType *PTy = dyn_cast<PointerType>($1.T->get());
1982 error("Cannot make null pointer constant with type: '" +
1983 $1.T->get()->getDescription() + "'");
1984 $$.C = ConstantPointerNull::get(PTy);
1989 $$.C = UndefValue::get($1.T->get());
1993 | Types SymbolicValueRef {
1994 const PointerType *Ty = dyn_cast<PointerType>($1.T->get());
1996 error("Global const reference must be a pointer type, not" +
1997 $1.T->get()->getDescription());
1999 // ConstExprs can exist in the body of a function, thus creating
2000 // GlobalValues whenever they refer to a variable. Because we are in
2001 // the context of a function, getExistingValue will search the functions
2002 // symbol table instead of the module symbol table for the global symbol,
2003 // which throws things all off. To get around this, we just tell
2004 // getExistingValue that we are at global scope here.
2006 Function *SavedCurFn = CurFun.CurrentFunction;
2007 CurFun.CurrentFunction = 0;
2008 Value *V = getExistingValue(Ty, $2);
2009 CurFun.CurrentFunction = SavedCurFn;
2011 // If this is an initializer for a constant pointer, which is referencing a
2012 // (currently) undefined variable, create a stub now that shall be replaced
2013 // in the future with the right type of variable.
2016 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2017 const PointerType *PT = cast<PointerType>(Ty);
2019 // First check to see if the forward references value is already created!
2020 PerModuleInfo::GlobalRefsType::iterator I =
2021 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2023 if (I != CurModule.GlobalRefs.end()) {
2024 V = I->second; // Placeholder already exists, use it...
2028 if ($2.Type == ValID::NameVal) Name = $2.Name;
2030 // Create the forward referenced global.
2032 if (const FunctionType *FTy =
2033 dyn_cast<FunctionType>(PT->getElementType())) {
2034 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2035 CurModule.CurrentModule);
2037 GV = new GlobalVariable(PT->getElementType(), false,
2038 GlobalValue::ExternalLinkage, 0,
2039 Name, CurModule.CurrentModule);
2042 // Keep track of the fact that we have a forward ref to recycle it
2043 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2047 $$.C = cast<GlobalValue>(V);
2049 delete $1.T; // Free the type handle
2052 if ($1.T->get() != $2.C->getType())
2053 error("Mismatched types for constant expression");
2058 | Types ZEROINITIALIZER {
2059 const Type *Ty = $1.T->get();
2060 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2061 error("Cannot create a null initialized value of this type");
2062 $$.C = Constant::getNullValue(Ty);
2066 | SIntType EINT64VAL { // integral constants
2067 const Type *Ty = $1.T;
2068 if (!ConstantInt::isValueValidForType(Ty, $2))
2069 error("Constant value doesn't fit in type");
2070 $$.C = ConstantInt::get(Ty, $2);
2073 | UIntType EUINT64VAL { // integral constants
2074 const Type *Ty = $1.T;
2075 if (!ConstantInt::isValueValidForType(Ty, $2))
2076 error("Constant value doesn't fit in type");
2077 $$.C = ConstantInt::get(Ty, $2);
2080 | BOOL TRUETOK { // Boolean constants
2081 $$.C = ConstantInt::get(Type::Int1Ty, true);
2084 | BOOL FALSETOK { // Boolean constants
2085 $$.C = ConstantInt::get(Type::Int1Ty, false);
2088 | FPType FPVAL { // Float & Double constants
2089 if (!ConstantFP::isValueValidForType($1.T, $2))
2090 error("Floating point constant invalid for type");
2091 $$.C = ConstantFP::get($1.T, $2);
2097 : CastOps '(' ConstVal TO Types ')' {
2098 const Type* SrcTy = $3.C->getType();
2099 const Type* DstTy = $5.T->get();
2100 Signedness SrcSign = $3.S;
2101 Signedness DstSign = $5.S;
2102 if (!SrcTy->isFirstClassType())
2103 error("cast constant expression from a non-primitive type: '" +
2104 SrcTy->getDescription() + "'");
2105 if (!DstTy->isFirstClassType())
2106 error("cast constant expression to a non-primitive type: '" +
2107 DstTy->getDescription() + "'");
2108 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2112 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2113 const Type *Ty = $3.C->getType();
2114 if (!isa<PointerType>(Ty))
2115 error("GetElementPtr requires a pointer operand");
2117 std::vector<Value*> VIndices;
2118 std::vector<Constant*> CIndices;
2119 upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2122 $$.C = ConstantExpr::getGetElementPtr($3.C, CIndices);
2125 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2126 if (!$3.C->getType()->isInteger() ||
2127 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2128 error("Select condition must be bool type");
2129 if ($5.C->getType() != $7.C->getType())
2130 error("Select operand types must match");
2131 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2134 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2135 const Type *Ty = $3.C->getType();
2136 if (Ty != $5.C->getType())
2137 error("Binary operator types must match");
2138 // First, make sure we're dealing with the right opcode by upgrading from
2139 // obsolete versions.
2140 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2142 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2143 // To retain backward compatibility with these early compilers, we emit a
2144 // cast to the appropriate integer type automatically if we are in the
2145 // broken case. See PR424 for more information.
2146 if (!isa<PointerType>(Ty)) {
2147 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2149 const Type *IntPtrTy = 0;
2150 switch (CurModule.CurrentModule->getPointerSize()) {
2151 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2152 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2153 default: error("invalid pointer binary constant expr");
2155 $$.C = ConstantExpr::get(Opcode,
2156 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2157 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2158 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2162 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2163 const Type* Ty = $3.C->getType();
2164 if (Ty != $5.C->getType())
2165 error("Logical operator types must match");
2166 if (!Ty->isInteger()) {
2167 if (!isa<PackedType>(Ty) ||
2168 !cast<PackedType>(Ty)->getElementType()->isInteger())
2169 error("Logical operator requires integer operands");
2171 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2172 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2175 | SetCondOps '(' ConstVal ',' ConstVal ')' {
2176 const Type* Ty = $3.C->getType();
2177 if (Ty != $5.C->getType())
2178 error("setcc operand types must match");
2179 unsigned short pred;
2180 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2181 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2184 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2185 if ($4.C->getType() != $6.C->getType())
2186 error("icmp operand types must match");
2187 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2190 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2191 if ($4.C->getType() != $6.C->getType())
2192 error("fcmp operand types must match");
2193 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2196 | ShiftOps '(' ConstVal ',' ConstVal ')' {
2197 if (!$5.C->getType()->isInteger() ||
2198 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2199 error("Shift count for shift constant must be unsigned byte");
2200 if (!$3.C->getType()->isInteger())
2201 error("Shift constant expression requires integer operand");
2202 $$.C = ConstantExpr::get(getOtherOp($1, $3.S), $3.C, $5.C);
2205 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2206 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2207 error("Invalid extractelement operands");
2208 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2211 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2212 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2213 error("Invalid insertelement operands");
2214 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2217 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2218 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2219 error("Invalid shufflevector operands");
2220 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2226 // ConstVector - A list of comma separated constants.
2228 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2230 $$ = new std::vector<ConstInfo>();
2236 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2238 : GLOBAL { $$ = false; }
2239 | CONSTANT { $$ = true; }
2243 //===----------------------------------------------------------------------===//
2244 // Rules to match Modules
2245 //===----------------------------------------------------------------------===//
2247 // Module rule: Capture the result of parsing the whole file into a result
2252 $$ = ParserResult = $1;
2253 CurModule.ModuleDone();
2257 // FunctionList - A list of functions, preceeded by a constant pool.
2260 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2261 | FunctionList FunctionProto { $$ = $1; }
2262 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2263 | FunctionList IMPLEMENTATION { $$ = $1; }
2265 $$ = CurModule.CurrentModule;
2266 // Emit an error if there are any unresolved types left.
2267 if (!CurModule.LateResolveTypes.empty()) {
2268 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2269 if (DID.Type == ValID::NameVal) {
2270 error("Reference to an undefined type: '"+DID.getName() + "'");
2272 error("Reference to an undefined type: #" + itostr(DID.Num));
2278 // ConstPool - Constants with optional names assigned to them.
2280 : ConstPool OptAssign TYPE TypesV {
2281 // Eagerly resolve types. This is not an optimization, this is a
2282 // requirement that is due to the fact that we could have this:
2284 // %list = type { %list * }
2285 // %list = type { %list * } ; repeated type decl
2287 // If types are not resolved eagerly, then the two types will not be
2288 // determined to be the same type!
2290 const Type* Ty = $4.T->get();
2291 ResolveTypeTo($2, Ty);
2293 if (!setTypeName(Ty, $2) && !$2) {
2294 // If this is a named type that is not a redefinition, add it to the slot
2296 CurModule.Types.push_back(Ty);
2300 | ConstPool FunctionProto { // Function prototypes can be in const pool
2302 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
2304 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2306 error("Global value initializer is not a constant");
2307 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C);
2308 } GlobalVarAttributes {
2311 | ConstPool OptAssign EXTERNAL GlobalType Types {
2312 const Type *Ty = $5.T->get();
2313 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0);
2315 } GlobalVarAttributes {
2318 | ConstPool OptAssign DLLIMPORT GlobalType Types {
2319 const Type *Ty = $5.T->get();
2320 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0);
2322 } GlobalVarAttributes {
2325 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2326 const Type *Ty = $5.T->get();
2328 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0);
2330 } GlobalVarAttributes {
2333 | ConstPool TARGET TargetDefinition {
2335 | ConstPool DEPLIBS '=' LibrariesDefinition {
2337 | /* empty: end of list */ {
2343 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2344 char *EndStr = UnEscapeLexed($1, true);
2345 std::string NewAsm($1, EndStr);
2348 if (AsmSoFar.empty())
2349 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2351 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2356 : BIG { $$ = Module::BigEndian; }
2357 | LITTLE { $$ = Module::LittleEndian; }
2361 : ENDIAN '=' BigOrLittle {
2362 CurModule.setEndianness($3);
2364 | POINTERSIZE '=' EUINT64VAL {
2366 CurModule.setPointerSize(Module::Pointer32);
2368 CurModule.setPointerSize(Module::Pointer64);
2370 error("Invalid pointer size: '" + utostr($3) + "'");
2372 | TRIPLE '=' STRINGCONSTANT {
2373 CurModule.CurrentModule->setTargetTriple($3);
2376 | DATALAYOUT '=' STRINGCONSTANT {
2377 CurModule.CurrentModule->setDataLayout($3);
2387 : LibList ',' STRINGCONSTANT {
2388 CurModule.CurrentModule->addLibrary($3);
2392 CurModule.CurrentModule->addLibrary($1);
2395 | /* empty: end of list */ { }
2398 //===----------------------------------------------------------------------===//
2399 // Rules to match Function Headers
2400 //===----------------------------------------------------------------------===//
2403 : VAR_ID | STRINGCONSTANT
2408 | /*empty*/ { $$ = 0; }
2413 if ($1.T->get() == Type::VoidTy)
2414 error("void typed arguments are invalid");
2415 $$ = new std::pair<PATypeInfo, char*>($1, $2);
2420 : ArgListH ',' ArgVal {
2426 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2433 : ArgListH { $$ = $1; }
2434 | ArgListH ',' DOTDOTDOT {
2437 VoidTI.T = new PATypeHolder(Type::VoidTy);
2438 VoidTI.S = Signless;
2439 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2442 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2444 VoidTI.T = new PATypeHolder(Type::VoidTy);
2445 VoidTI.S = Signless;
2446 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2448 | /* empty */ { $$ = 0; }
2452 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2454 std::string FunctionName($3);
2455 free($3); // Free strdup'd memory!
2457 const Type* RetTy = $2.T->get();
2459 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2460 error("LLVM functions cannot return aggregate types");
2462 std::vector<const Type*> ParamTypeList;
2464 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2465 // i8*. We check here for those names and override the parameter list
2466 // types to ensure the prototype is correct.
2467 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2468 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2469 } else if (FunctionName == "llvm.va_copy") {
2470 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2471 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2472 } else if ($5) { // If there are arguments...
2473 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2474 I = $5->begin(), E = $5->end(); I != E; ++I) {
2475 const Type *Ty = I->first.T->get();
2476 ParamTypeList.push_back(Ty);
2481 ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2482 if (isVarArg) ParamTypeList.pop_back();
2484 const FunctionType *FT = FunctionType::get(RetTy, ParamTypeList, isVarArg);
2485 const PointerType *PFT = PointerType::get(FT);
2489 if (!FunctionName.empty()) {
2490 ID = ValID::create((char*)FunctionName.c_str());
2492 ID = ValID::create((int)CurModule.Values[PFT].size());
2496 // See if this function was forward referenced. If so, recycle the object.
2497 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2498 // Move the function to the end of the list, from whereever it was
2499 // previously inserted.
2500 Fn = cast<Function>(FWRef);
2501 CurModule.CurrentModule->getFunctionList().remove(Fn);
2502 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2503 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2504 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2505 // If this is the case, either we need to be a forward decl, or it needs
2507 if (!CurFun.isDeclare && !Fn->isExternal())
2508 error("Redefinition of function '" + FunctionName + "'");
2510 // Make sure to strip off any argument names so we can't get conflicts.
2511 if (Fn->isExternal())
2512 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2515 } else { // Not already defined?
2516 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2517 CurModule.CurrentModule);
2519 InsertValue(Fn, CurModule.Values);
2522 CurFun.FunctionStart(Fn);
2524 if (CurFun.isDeclare) {
2525 // If we have declaration, always overwrite linkage. This will allow us
2526 // to correctly handle cases, when pointer to function is passed as
2527 // argument to another function.
2528 Fn->setLinkage(CurFun.Linkage);
2530 Fn->setCallingConv($1);
2531 Fn->setAlignment($8);
2537 // Add all of the arguments we parsed to the function...
2538 if ($5) { // Is null if empty...
2539 if (isVarArg) { // Nuke the last entry
2540 assert($5->back().first.T->get() == Type::VoidTy &&
2541 $5->back().second == 0 && "Not a varargs marker");
2542 delete $5->back().first.T;
2543 $5->pop_back(); // Delete the last entry
2545 Function::arg_iterator ArgIt = Fn->arg_begin();
2546 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2547 I = $5->begin(), E = $5->end(); I != E; ++I, ++ArgIt) {
2548 delete I->first.T; // Delete the typeholder...
2549 setValueName(ArgIt, I->second); // Insert arg into symtab...
2552 delete $5; // We're now done with the argument list
2558 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
2562 : OptLinkage FunctionHeaderH BEGIN {
2563 $$ = CurFun.CurrentFunction;
2565 // Make sure that we keep track of the linkage type even if there was a
2566 // previous "declare".
2572 : ENDTOK | '}' // Allow end of '}' to end a function
2576 : BasicBlockList END {
2582 | DLLIMPORT { CurFun.Linkage = GlobalValue::DLLImportLinkage; }
2583 | EXTERN_WEAK { CurFun.Linkage = GlobalValue::ExternalWeakLinkage; }
2587 : DECLARE { CurFun.isDeclare = true; } FnDeclareLinkage FunctionHeaderH {
2588 $$ = CurFun.CurrentFunction;
2589 CurFun.FunctionDone();
2594 //===----------------------------------------------------------------------===//
2595 // Rules to match Basic Blocks
2596 //===----------------------------------------------------------------------===//
2599 : /* empty */ { $$ = false; }
2600 | SIDEEFFECT { $$ = true; }
2604 // A reference to a direct constant
2605 : ESINT64VAL { $$ = ValID::create($1); }
2606 | EUINT64VAL { $$ = ValID::create($1); }
2607 | FPVAL { $$ = ValID::create($1); }
2608 | TRUETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true)); }
2609 | FALSETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false)); }
2610 | NULL_TOK { $$ = ValID::createNull(); }
2611 | UNDEF { $$ = ValID::createUndef(); }
2612 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
2613 | '<' ConstVector '>' { // Nonempty unsized packed vector
2614 const Type *ETy = (*$2)[0].C->getType();
2615 int NumElements = $2->size();
2616 PackedType* pt = PackedType::get(ETy, NumElements);
2617 PATypeHolder* PTy = new PATypeHolder(
2618 HandleUpRefs(PackedType::get(ETy, NumElements)));
2620 // Verify all elements are correct type!
2621 std::vector<Constant*> Elems;
2622 for (unsigned i = 0; i < $2->size(); i++) {
2623 Constant *C = (*$2)[i].C;
2624 const Type *CTy = C->getType();
2626 error("Element #" + utostr(i) + " is not of type '" +
2627 ETy->getDescription() +"' as required!\nIt is of type '" +
2628 CTy->getDescription() + "'");
2631 $$ = ValID::create(ConstantPacked::get(pt, Elems));
2632 delete PTy; delete $2;
2635 $$ = ValID::create($1.C);
2637 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2638 char *End = UnEscapeLexed($3, true);
2639 std::string AsmStr = std::string($3, End);
2640 End = UnEscapeLexed($5, true);
2641 std::string Constraints = std::string($5, End);
2642 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2648 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2652 : INTVAL { $$ = ValID::create($1); }
2653 | Name { $$ = ValID::create($1); }
2656 // ValueRef - A reference to a definition... either constant or symbolic
2658 : SymbolicValueRef | ConstValueRef
2662 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2663 // type immediately preceeds the value reference, and allows complex constant
2664 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2667 const Type *Ty = $1.T->get();
2669 $$.V = getVal(Ty, $2);
2675 : BasicBlockList BasicBlock {
2678 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2683 // Basic blocks are terminated by branching instructions:
2684 // br, br/cc, switch, ret
2687 : InstructionList OptAssign BBTerminatorInst {
2688 setValueName($3, $2);
2690 $1->getInstList().push_back($3);
2697 : InstructionList Inst {
2699 $1->getInstList().push_back($2.I);
2703 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2704 // Make sure to move the basic block to the correct location in the
2705 // function, instead of leaving it inserted wherever it was first
2707 Function::BasicBlockListType &BBL =
2708 CurFun.CurrentFunction->getBasicBlockList();
2709 BBL.splice(BBL.end(), BBL, $$);
2712 $$ = CurBB = getBBVal(ValID::create($1), true);
2713 // Make sure to move the basic block to the correct location in the
2714 // function, instead of leaving it inserted wherever it was first
2716 Function::BasicBlockListType &BBL =
2717 CurFun.CurrentFunction->getBasicBlockList();
2718 BBL.splice(BBL.end(), BBL, $$);
2722 Unwind : UNWIND | EXCEPT;
2725 : RET ResolvedVal { // Return with a result...
2726 $$ = new ReturnInst($2.V);
2728 | RET VOID { // Return with no result...
2729 $$ = new ReturnInst();
2731 | BR LABEL ValueRef { // Unconditional Branch...
2732 BasicBlock* tmpBB = getBBVal($3);
2733 $$ = new BranchInst(tmpBB);
2734 } // Conditional Branch...
2735 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2736 BasicBlock* tmpBBA = getBBVal($6);
2737 BasicBlock* tmpBBB = getBBVal($9);
2738 Value* tmpVal = getVal(Type::Int1Ty, $3);
2739 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2741 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2742 Value* tmpVal = getVal($2.T, $3);
2743 BasicBlock* tmpBB = getBBVal($6);
2744 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2746 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2748 for (; I != E; ++I) {
2749 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2750 S->addCase(CI, I->second);
2752 error("Switch case is constant, but not a simple integer");
2756 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2757 Value* tmpVal = getVal($2.T, $3);
2758 BasicBlock* tmpBB = getBBVal($6);
2759 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2762 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2763 TO LABEL ValueRef Unwind LABEL ValueRef {
2764 const PointerType *PFTy;
2765 const FunctionType *Ty;
2767 if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
2768 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2769 // Pull out the types of all of the arguments...
2770 std::vector<const Type*> ParamTypes;
2772 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
2774 ParamTypes.push_back((*I).V->getType());
2776 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2777 if (isVarArg) ParamTypes.pop_back();
2778 Ty = FunctionType::get($3.T->get(), ParamTypes, isVarArg);
2779 PFTy = PointerType::get(Ty);
2781 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2782 BasicBlock *Normal = getBBVal($10);
2783 BasicBlock *Except = getBBVal($13);
2785 // Create the call node...
2786 if (!$6) { // Has no arguments?
2787 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2788 } else { // Has arguments?
2789 // Loop through FunctionType's arguments and ensure they are specified
2792 FunctionType::param_iterator I = Ty->param_begin();
2793 FunctionType::param_iterator E = Ty->param_end();
2794 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
2796 std::vector<Value*> Args;
2797 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2798 if ((*ArgI).V->getType() != *I)
2799 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
2800 (*I)->getDescription() + "'");
2801 Args.push_back((*ArgI).V);
2804 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2805 error("Invalid number of parameters detected");
2807 $$ = new InvokeInst(V, Normal, Except, Args);
2809 cast<InvokeInst>($$)->setCallingConv($2);
2814 $$ = new UnwindInst();
2817 $$ = new UnreachableInst();
2822 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2824 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
2827 error("May only switch on a constant pool value");
2829 BasicBlock* tmpBB = getBBVal($6);
2830 $$->push_back(std::make_pair(V, tmpBB));
2832 | IntType ConstValueRef ',' LABEL ValueRef {
2833 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2834 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
2837 error("May only switch on a constant pool value");
2839 BasicBlock* tmpBB = getBBVal($5);
2840 $$->push_back(std::make_pair(V, tmpBB));
2845 : OptAssign InstVal {
2848 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
2849 if (BCI->getSrcTy() == BCI->getDestTy() &&
2850 BCI->getOperand(0)->getName() == $1)
2851 // This is a useless bit cast causing a name redefinition. It is
2852 // a bit cast from a type to the same type of an operand with the
2853 // same name as the name we would give this instruction. Since this
2854 // instruction results in no code generation, it is safe to omit
2855 // the instruction. This situation can occur because of collapsed
2856 // type planes. For example:
2857 // %X = add int %Y, %Z
2858 // %X = cast int %Y to uint
2859 // After upgrade, this looks like:
2860 // %X = add i32 %Y, %Z
2861 // %X = bitcast i32 to i32
2862 // The bitcast is clearly useless so we omit it.
2868 setValueName($2.I, $1);
2874 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2875 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
2877 Value* tmpVal = getVal($1.T->get(), $3);
2878 BasicBlock* tmpBB = getBBVal($5);
2879 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
2882 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2884 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
2885 BasicBlock* tmpBB = getBBVal($6);
2886 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
2890 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
2891 $$ = new std::vector<ValueInfo>();
2894 | ValueRefList ',' ResolvedVal {
2899 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2902 | /*empty*/ { $$ = 0; }
2915 : ArithmeticOps Types ValueRef ',' ValueRef {
2916 const Type* Ty = $2.T->get();
2917 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<PackedType>(Ty))
2918 error("Arithmetic operator requires integer, FP, or packed operands");
2919 if (isa<PackedType>(Ty) &&
2920 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
2921 error("Remainder not supported on packed types");
2922 // Upgrade the opcode from obsolete versions before we do anything with it.
2923 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
2924 Value* val1 = getVal(Ty, $3);
2925 Value* val2 = getVal(Ty, $5);
2926 $$.I = BinaryOperator::create(Opcode, val1, val2);
2928 error("binary operator returned null");
2932 | LogicalOps Types ValueRef ',' ValueRef {
2933 const Type *Ty = $2.T->get();
2934 if (!Ty->isInteger()) {
2935 if (!isa<PackedType>(Ty) ||
2936 !cast<PackedType>(Ty)->getElementType()->isInteger())
2937 error("Logical operator requires integral operands");
2939 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
2940 Value* tmpVal1 = getVal(Ty, $3);
2941 Value* tmpVal2 = getVal(Ty, $5);
2942 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
2944 error("binary operator returned null");
2948 | SetCondOps Types ValueRef ',' ValueRef {
2949 const Type* Ty = $2.T->get();
2950 if(isa<PackedType>(Ty))
2951 error("PackedTypes currently not supported in setcc instructions");
2952 unsigned short pred;
2953 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
2954 Value* tmpVal1 = getVal(Ty, $3);
2955 Value* tmpVal2 = getVal(Ty, $5);
2956 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
2958 error("binary operator returned null");
2962 | ICMP IPredicates Types ValueRef ',' ValueRef {
2963 const Type *Ty = $3.T->get();
2964 if (isa<PackedType>(Ty))
2965 error("PackedTypes currently not supported in icmp instructions");
2966 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
2967 error("icmp requires integer or pointer typed operands");
2968 Value* tmpVal1 = getVal(Ty, $4);
2969 Value* tmpVal2 = getVal(Ty, $6);
2970 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
2974 | FCMP FPredicates Types ValueRef ',' ValueRef {
2975 const Type *Ty = $3.T->get();
2976 if (isa<PackedType>(Ty))
2977 error("PackedTypes currently not supported in fcmp instructions");
2978 else if (!Ty->isFloatingPoint())
2979 error("fcmp instruction requires floating point operands");
2980 Value* tmpVal1 = getVal(Ty, $4);
2981 Value* tmpVal2 = getVal(Ty, $6);
2982 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
2987 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
2988 const Type *Ty = $2.V->getType();
2989 Value *Ones = ConstantInt::getAllOnesValue(Ty);
2991 error("Expected integral type for not instruction");
2992 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
2994 error("Could not create a xor instruction");
2997 | ShiftOps ResolvedVal ',' ResolvedVal {
2998 if (!$4.V->getType()->isInteger() ||
2999 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3000 error("Shift amount must be int8");
3001 if (!$2.V->getType()->isInteger())
3002 error("Shift constant expression requires integer operand");
3003 $$.I = new ShiftInst(getOtherOp($1, $2.S), $2.V, $4.V);
3006 | CastOps ResolvedVal TO Types {
3007 const Type *DstTy = $4.T->get();
3008 if (!DstTy->isFirstClassType())
3009 error("cast instruction to a non-primitive type: '" +
3010 DstTy->getDescription() + "'");
3011 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3015 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3016 if (!$2.V->getType()->isInteger() ||
3017 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3018 error("select condition must be bool");
3019 if ($4.V->getType() != $6.V->getType())
3020 error("select value types should match");
3021 $$.I = new SelectInst($2.V, $4.V, $6.V);
3024 | VAARG ResolvedVal ',' Types {
3025 const Type *Ty = $4.T->get();
3027 $$.I = new VAArgInst($2.V, Ty);
3031 | VAARG_old ResolvedVal ',' Types {
3032 const Type* ArgTy = $2.V->getType();
3033 const Type* DstTy = $4.T->get();
3034 ObsoleteVarArgs = true;
3035 Function* NF = cast<Function>(CurModule.CurrentModule->
3036 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3039 //foo = alloca 1 of t
3043 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3044 CurBB->getInstList().push_back(foo);
3045 CallInst* bar = new CallInst(NF, $2.V);
3046 CurBB->getInstList().push_back(bar);
3047 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3048 $$.I = new VAArgInst(foo, DstTy);
3052 | VANEXT_old ResolvedVal ',' Types {
3053 const Type* ArgTy = $2.V->getType();
3054 const Type* DstTy = $4.T->get();
3055 ObsoleteVarArgs = true;
3056 Function* NF = cast<Function>(CurModule.CurrentModule->
3057 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3059 //b = vanext a, t ->
3060 //foo = alloca 1 of t
3063 //tmp = vaarg foo, t
3065 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3066 CurBB->getInstList().push_back(foo);
3067 CallInst* bar = new CallInst(NF, $2.V);
3068 CurBB->getInstList().push_back(bar);
3069 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3070 Instruction* tmp = new VAArgInst(foo, DstTy);
3071 CurBB->getInstList().push_back(tmp);
3072 $$.I = new LoadInst(foo);
3076 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3077 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3078 error("Invalid extractelement operands");
3079 $$.I = new ExtractElementInst($2.V, $4.V);
3082 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3083 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3084 error("Invalid insertelement operands");
3085 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3088 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3089 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3090 error("Invalid shufflevector operands");
3091 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3095 const Type *Ty = $2.P->front().first->getType();
3096 if (!Ty->isFirstClassType())
3097 error("PHI node operands must be of first class type");
3098 PHINode *PHI = new PHINode(Ty);
3099 PHI->reserveOperandSpace($2.P->size());
3100 while ($2.P->begin() != $2.P->end()) {
3101 if ($2.P->front().first->getType() != Ty)
3102 error("All elements of a PHI node must be of the same type");
3103 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3108 delete $2.P; // Free the list...
3110 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
3112 // Handle the short call syntax
3113 const PointerType *PFTy;
3114 const FunctionType *FTy;
3115 if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
3116 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3117 // Pull out the types of all of the arguments...
3118 std::vector<const Type*> ParamTypes;
3120 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3122 ParamTypes.push_back((*I).V->getType());
3125 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3126 if (isVarArg) ParamTypes.pop_back();
3128 const Type *RetTy = $3.T->get();
3129 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3130 error("Functions cannot return aggregate types");
3132 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg);
3133 PFTy = PointerType::get(FTy);
3136 // First upgrade any intrinsic calls.
3137 std::vector<Value*> Args;
3139 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3140 Args.push_back((*$6)[i].V);
3141 Instruction *Inst = upgradeIntrinsicCall(FTy, $4, Args);
3143 // If we got an upgraded intrinsic
3148 // Get the function we're calling
3149 Value *V = getVal(PFTy, $4);
3151 // Check the argument values match
3152 if (!$6) { // Has no arguments?
3153 // Make sure no arguments is a good thing!
3154 if (FTy->getNumParams() != 0)
3155 error("No arguments passed to a function that expects arguments");
3156 } else { // Has arguments?
3157 // Loop through FunctionType's arguments and ensure they are specified
3160 FunctionType::param_iterator I = FTy->param_begin();
3161 FunctionType::param_iterator E = FTy->param_end();
3162 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3164 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3165 if ((*ArgI).V->getType() != *I)
3166 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3167 (*I)->getDescription() + "'");
3169 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3170 error("Invalid number of parameters detected");
3173 // Create the call instruction
3174 CallInst *CI = new CallInst(V, Args);
3175 CI->setTailCall($1);
3176 CI->setCallingConv($2);
3189 // IndexList - List of indices for GEP based instructions...
3191 : ',' ValueRefList { $$ = $2; }
3192 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3196 : VOLATILE { $$ = true; }
3197 | /* empty */ { $$ = false; }
3201 : MALLOC Types OptCAlign {
3202 const Type *Ty = $2.T->get();
3204 $$.I = new MallocInst(Ty, 0, $3);
3207 | MALLOC Types ',' UINT ValueRef OptCAlign {
3208 const Type *Ty = $2.T->get();
3210 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3213 | ALLOCA Types OptCAlign {
3214 const Type *Ty = $2.T->get();
3216 $$.I = new AllocaInst(Ty, 0, $3);
3219 | ALLOCA Types ',' UINT ValueRef OptCAlign {
3220 const Type *Ty = $2.T->get();
3222 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3225 | FREE ResolvedVal {
3226 const Type *PTy = $2.V->getType();
3227 if (!isa<PointerType>(PTy))
3228 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3229 $$.I = new FreeInst($2.V);
3232 | OptVolatile LOAD Types ValueRef {
3233 const Type* Ty = $3.T->get();
3235 if (!isa<PointerType>(Ty))
3236 error("Can't load from nonpointer type: " + Ty->getDescription());
3237 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3238 error("Can't load from pointer of non-first-class type: " +
3239 Ty->getDescription());
3240 Value* tmpVal = getVal(Ty, $4);
3241 $$.I = new LoadInst(tmpVal, "", $1);
3244 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3245 const PointerType *PTy = dyn_cast<PointerType>($5.T->get());
3247 error("Can't store to a nonpointer type: " +
3248 $5.T->get()->getDescription());
3249 const Type *ElTy = PTy->getElementType();
3250 if (ElTy != $3.V->getType())
3251 error("Can't store '" + $3.V->getType()->getDescription() +
3252 "' into space of type '" + ElTy->getDescription() + "'");
3253 Value* tmpVal = getVal(PTy, $6);
3254 $$.I = new StoreInst($3.V, tmpVal, $1);
3258 | GETELEMENTPTR Types ValueRef IndexList {
3259 const Type* Ty = $2.T->get();
3260 if (!isa<PointerType>(Ty))
3261 error("getelementptr insn requires pointer operand");
3263 std::vector<Value*> VIndices;
3264 upgradeGEPIndices(Ty, $4, VIndices);
3266 Value* tmpVal = getVal(Ty, $3);
3267 $$.I = new GetElementPtrInst(tmpVal, VIndices);
3276 int yyerror(const char *ErrorMsg) {
3278 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3279 + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3280 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3281 if (yychar != YYEMPTY && yychar != 0)
3282 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3284 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3285 std::cout << "llvm-upgrade: parse failed.\n";
3289 void warning(const std::string& ErrorMsg) {
3291 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3292 + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3293 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3294 if (yychar != YYEMPTY && yychar != 0)
3295 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3297 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3300 void error(const std::string& ErrorMsg, int LineNo) {
3301 if (LineNo == -1) LineNo = Upgradelineno;
3302 Upgradelineno = LineNo;
3303 yyerror(ErrorMsg.c_str());