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;
177 inline PerFunctionInfo() {
180 Linkage = GlobalValue::ExternalLinkage;
183 inline void FunctionStart(Function *M) {
188 void FunctionDone() {
189 NumberedBlocks.clear();
191 // Any forward referenced blocks left?
192 if (!BBForwardRefs.empty()) {
193 error("Undefined reference to label " +
194 BBForwardRefs.begin()->first->getName());
198 // Resolve all forward references now.
199 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
201 Values.clear(); // Clear out function local definitions
205 Linkage = GlobalValue::ExternalLinkage;
207 } CurFun; // Info for the current function...
209 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
212 //===----------------------------------------------------------------------===//
213 // Code to handle definitions of all the types
214 //===----------------------------------------------------------------------===//
216 static int InsertValue(Value *V,
217 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
218 if (V->hasName()) return -1; // Is this a numbered definition?
220 // Yes, insert the value into the value table...
221 ValueList &List = ValueTab[V->getType()];
223 return List.size()-1;
226 static const Type *getType(const ValID &D, bool DoNotImprovise = false) {
228 case ValID::NumberVal: // Is it a numbered definition?
229 // Module constants occupy the lowest numbered slots...
230 if ((unsigned)D.Num < CurModule.Types.size()) {
231 return CurModule.Types[(unsigned)D.Num];
234 case ValID::NameVal: // Is it a named definition?
235 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
236 D.destroy(); // Free old strdup'd memory...
241 error("Internal parser error: Invalid symbol type reference");
245 // If we reached here, we referenced either a symbol that we don't know about
246 // or an id number that hasn't been read yet. We may be referencing something
247 // forward, so just create an entry to be resolved later and get to it...
249 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
252 if (inFunctionScope()) {
253 if (D.Type == ValID::NameVal) {
254 error("Reference to an undefined type: '" + D.getName() + "'");
257 error("Reference to an undefined type: #" + itostr(D.Num));
262 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
263 if (I != CurModule.LateResolveTypes.end())
266 Type *Typ = OpaqueType::get();
267 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
271 // getExistingValue - Look up the value specified by the provided type and
272 // the provided ValID. If the value exists and has already been defined, return
273 // it. Otherwise return null.
275 static Value *getExistingValue(const Type *Ty, const ValID &D) {
276 if (isa<FunctionType>(Ty)) {
277 error("Functions are not values and must be referenced as pointers");
281 case ValID::NumberVal: { // Is it a numbered definition?
282 unsigned Num = (unsigned)D.Num;
284 // Module constants occupy the lowest numbered slots...
285 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
286 if (VI != CurModule.Values.end()) {
287 if (Num < VI->second.size())
288 return VI->second[Num];
289 Num -= VI->second.size();
292 // Make sure that our type is within bounds
293 VI = CurFun.Values.find(Ty);
294 if (VI == CurFun.Values.end()) return 0;
296 // Check that the number is within bounds...
297 if (VI->second.size() <= Num) return 0;
299 return VI->second[Num];
302 case ValID::NameVal: { // Is it a named definition?
303 // Get the name out of the ID
304 std::string Name(D.Name);
306 RenameMapKey Key = std::make_pair(Name, Ty);
307 if (inFunctionScope()) {
308 // See if the name was renamed
309 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
310 std::string LookupName;
311 if (I != CurFun.RenameMap.end())
312 LookupName = I->second;
315 SymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
316 V = SymTab.lookup(Ty, LookupName);
319 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
320 std::string LookupName;
321 if (I != CurModule.RenameMap.end())
322 LookupName = I->second;
325 V = CurModule.CurrentModule->getValueSymbolTable().lookup(Ty, LookupName);
330 D.destroy(); // Free old strdup'd memory...
334 // Check to make sure that "Ty" is an integral type, and that our
335 // value will fit into the specified type...
336 case ValID::ConstSIntVal: // Is it a constant pool reference??
337 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
338 error("Signed integral constant '" + itostr(D.ConstPool64) +
339 "' is invalid for type '" + Ty->getDescription() + "'");
341 return ConstantInt::get(Ty, D.ConstPool64);
343 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
344 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
345 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
346 error("Integral constant '" + utostr(D.UConstPool64) +
347 "' is invalid or out of range");
348 else // This is really a signed reference. Transmogrify.
349 return ConstantInt::get(Ty, D.ConstPool64);
351 return ConstantInt::get(Ty, D.UConstPool64);
353 case ValID::ConstFPVal: // Is it a floating point const pool reference?
354 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
355 error("FP constant invalid for type");
356 return ConstantFP::get(Ty, D.ConstPoolFP);
358 case ValID::ConstNullVal: // Is it a null value?
359 if (!isa<PointerType>(Ty))
360 error("Cannot create a a non pointer null");
361 return ConstantPointerNull::get(cast<PointerType>(Ty));
363 case ValID::ConstUndefVal: // Is it an undef value?
364 return UndefValue::get(Ty);
366 case ValID::ConstZeroVal: // Is it a zero value?
367 return Constant::getNullValue(Ty);
369 case ValID::ConstantVal: // Fully resolved constant?
370 if (D.ConstantValue->getType() != Ty)
371 error("Constant expression type different from required type");
372 return D.ConstantValue;
374 case ValID::InlineAsmVal: { // Inline asm expression
375 const PointerType *PTy = dyn_cast<PointerType>(Ty);
376 const FunctionType *FTy =
377 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
378 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
379 error("Invalid type for asm constraint string");
380 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
381 D.IAD->HasSideEffects);
382 D.destroy(); // Free InlineAsmDescriptor.
386 assert(0 && "Unhandled case");
390 assert(0 && "Unhandled case");
394 // getVal - This function is identical to getExistingValue, except that if a
395 // value is not already defined, it "improvises" by creating a placeholder var
396 // that looks and acts just like the requested variable. When the value is
397 // defined later, all uses of the placeholder variable are replaced with the
400 static Value *getVal(const Type *Ty, const ValID &ID) {
401 if (Ty == Type::LabelTy)
402 error("Cannot use a basic block here");
404 // See if the value has already been defined.
405 Value *V = getExistingValue(Ty, ID);
408 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
409 error("Invalid use of a composite type");
411 // If we reached here, we referenced either a symbol that we don't know about
412 // or an id number that hasn't been read yet. We may be referencing something
413 // forward, so just create an entry to be resolved later and get to it...
414 V = new Argument(Ty);
416 // Remember where this forward reference came from. FIXME, shouldn't we try
417 // to recycle these things??
418 CurModule.PlaceHolderInfo.insert(
419 std::make_pair(V, std::make_pair(ID, Upgradelineno-1)));
421 if (inFunctionScope())
422 InsertValue(V, CurFun.LateResolveValues);
424 InsertValue(V, CurModule.LateResolveValues);
428 /// getBBVal - This is used for two purposes:
429 /// * If isDefinition is true, a new basic block with the specified ID is being
431 /// * If isDefinition is true, this is a reference to a basic block, which may
432 /// or may not be a forward reference.
434 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
435 assert(inFunctionScope() && "Can't get basic block at global scope");
441 error("Illegal label reference " + ID.getName());
443 case ValID::NumberVal: // Is it a numbered definition?
444 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
445 CurFun.NumberedBlocks.resize(ID.Num+1);
446 BB = CurFun.NumberedBlocks[ID.Num];
448 case ValID::NameVal: // Is it a named definition?
450 if (Value *N = CurFun.CurrentFunction->
451 getValueSymbolTable().lookup(Type::LabelTy, Name)) {
452 if (N->getType() != Type::LabelTy)
453 error("Name '" + Name + "' does not refer to a BasicBlock");
454 BB = cast<BasicBlock>(N);
459 // See if the block has already been defined.
461 // If this is the definition of the block, make sure the existing value was
462 // just a forward reference. If it was a forward reference, there will be
463 // an entry for it in the PlaceHolderInfo map.
464 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
465 // The existing value was a definition, not a forward reference.
466 error("Redefinition of label " + ID.getName());
468 ID.destroy(); // Free strdup'd memory.
472 // Otherwise this block has not been seen before.
473 BB = new BasicBlock("", CurFun.CurrentFunction);
474 if (ID.Type == ValID::NameVal) {
475 BB->setName(ID.Name);
477 CurFun.NumberedBlocks[ID.Num] = BB;
480 // If this is not a definition, keep track of it so we can use it as a forward
483 // Remember where this forward reference came from.
484 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
486 // The forward declaration could have been inserted anywhere in the
487 // function: insert it into the correct place now.
488 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
489 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
496 //===----------------------------------------------------------------------===//
497 // Code to handle forward references in instructions
498 //===----------------------------------------------------------------------===//
500 // This code handles the late binding needed with statements that reference
501 // values not defined yet... for example, a forward branch, or the PHI node for
504 // This keeps a table (CurFun.LateResolveValues) of all such forward references
505 // and back patchs after we are done.
508 /// This function determines if two function types differ only in their use of
509 /// the sret parameter attribute in the first argument. If they are identical
510 /// in all other respects, it returns true. Otherwise, it returns false.
511 bool FuncTysDifferOnlyBySRet(const FunctionType *F1,
512 const FunctionType *F2) {
513 if (F1->getReturnType() != F2->getReturnType() ||
514 F1->getNumParams() != F2->getNumParams() ||
515 F1->getParamAttrs(0) != F2->getParamAttrs(0))
517 unsigned SRetMask = ~unsigned(FunctionType::StructRetAttribute);
518 for (unsigned i = 0; i < F1->getNumParams(); ++i) {
519 if (F1->getParamType(i) != F2->getParamType(i) ||
520 unsigned(F1->getParamAttrs(i+1)) & SRetMask !=
521 unsigned(F2->getParamAttrs(i+1)) & SRetMask)
527 // ResolveDefinitions - If we could not resolve some defs at parsing
528 // time (forward branches, phi functions for loops, etc...) resolve the
532 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
533 std::map<const Type*,ValueList> *FutureLateResolvers) {
534 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
535 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
536 E = LateResolvers.end(); LRI != E; ++LRI) {
537 ValueList &List = LRI->second;
538 while (!List.empty()) {
539 Value *V = List.back();
542 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
543 CurModule.PlaceHolderInfo.find(V);
544 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
546 ValID &DID = PHI->second.first;
548 Value *TheRealValue = getExistingValue(LRI->first, DID);
550 V->replaceAllUsesWith(TheRealValue);
552 CurModule.PlaceHolderInfo.erase(PHI);
553 } else if (FutureLateResolvers) {
554 // Functions have their unresolved items forwarded to the module late
556 InsertValue(V, *FutureLateResolvers);
558 if (DID.Type == ValID::NameVal) {
559 // The upgrade of csretcc to sret param attribute may have caused a
560 // function to not be found because the param attribute changed the
561 // type of the called function. Detect this situation and insert a
562 // cast as necessary.
564 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
565 if (const FunctionType *FTy =
566 dyn_cast<FunctionType>(PTy->getElementType()))
567 if (Function *OtherF =
568 CurModule.CurrentModule->getNamedFunction(DID.getName()))
569 if (FuncTysDifferOnlyBySRet(FTy,OtherF->getFunctionType())) {
570 V->replaceAllUsesWith(ConstantExpr::getBitCast(OtherF, PTy));
574 error("Reference to an invalid definition: '" +DID.getName()+
575 "' of type '" + V->getType()->getDescription() + "'",
580 error("Reference to an invalid definition: #" +
581 itostr(DID.Num) + " of type '" +
582 V->getType()->getDescription() + "'", PHI->second.second);
589 LateResolvers.clear();
592 // ResolveTypeTo - A brand new type was just declared. This means that (if
593 // name is not null) things referencing Name can be resolved. Otherwise, things
594 // refering to the number can be resolved. Do this now.
596 static void ResolveTypeTo(char *Name, const Type *ToTy) {
598 if (Name) D = ValID::create(Name);
599 else D = ValID::create((int)CurModule.Types.size());
601 std::map<ValID, PATypeHolder>::iterator I =
602 CurModule.LateResolveTypes.find(D);
603 if (I != CurModule.LateResolveTypes.end()) {
604 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
605 CurModule.LateResolveTypes.erase(I);
609 /// @brief This just makes any name given to it unique, up to MAX_UINT times.
610 static std::string makeNameUnique(const std::string& Name) {
611 static unsigned UniqueNameCounter = 1;
612 std::string Result(Name);
613 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
617 /// This is the implementation portion of TypeHasInteger. It traverses the
618 /// type given, avoiding recursive types, and returns true as soon as it finds
619 /// an integer type. If no integer type is found, it returns false.
620 static bool TypeHasIntegerI(const Type *Ty, std::vector<const Type*> Stack) {
621 // Handle some easy cases
622 if (Ty->isPrimitiveType() || (Ty->getTypeID() == Type::OpaqueTyID))
626 if (const SequentialType *STy = dyn_cast<SequentialType>(Ty))
627 return STy->getElementType()->isInteger();
629 // Avoid type structure recursion
630 for (std::vector<const Type*>::iterator I = Stack.begin(), E = Stack.end();
635 // Push us on the type stack
638 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
639 if (TypeHasIntegerI(FTy->getReturnType(), Stack))
641 FunctionType::param_iterator I = FTy->param_begin();
642 FunctionType::param_iterator E = FTy->param_end();
644 if (TypeHasIntegerI(*I, Stack))
647 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
648 StructType::element_iterator I = STy->element_begin();
649 StructType::element_iterator E = STy->element_end();
650 for (; I != E; ++I) {
651 if (TypeHasIntegerI(*I, Stack))
656 // There shouldn't be anything else, but its definitely not integer
657 assert(0 && "What type is this?");
661 /// This is the interface to TypeHasIntegerI. It just provides the type stack,
662 /// to avoid recursion, and then calls TypeHasIntegerI.
663 static inline bool TypeHasInteger(const Type *Ty) {
664 std::vector<const Type*> TyStack;
665 return TypeHasIntegerI(Ty, TyStack);
668 // setValueName - Set the specified value to the name given. The name may be
669 // null potentially, in which case this is a noop. The string passed in is
670 // assumed to be a malloc'd string buffer, and is free'd by this function.
672 static void setValueName(Value *V, char *NameStr) {
674 std::string Name(NameStr); // Copy string
675 free(NameStr); // Free old string
677 if (V->getType() == Type::VoidTy) {
678 error("Can't assign name '" + Name + "' to value with void type");
682 assert(inFunctionScope() && "Must be in function scope");
684 // Search the function's symbol table for an existing value of this name
686 SymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
687 SymbolTable::plane_const_iterator PI = ST.plane_begin(), PE =ST.plane_end();
688 for ( ; PI != PE; ++PI) {
689 SymbolTable::value_const_iterator VI = PI->second.find(Name);
690 if (VI != PI->second.end()) {
691 Existing = VI->second;
696 // An existing value of the same name was found. This might have happened
697 // because of the integer type planes collapsing in LLVM 2.0.
698 if (Existing->getType() == V->getType() &&
699 !TypeHasInteger(Existing->getType())) {
700 // If the type does not contain any integers in them then this can't be
701 // a type plane collapsing issue. It truly is a redefinition and we
702 // should error out as the assembly is invalid.
703 error("Redefinition of value named '" + Name + "' of type '" +
704 V->getType()->getDescription() + "'");
707 // In LLVM 2.0 we don't allow names to be re-used for any values in a
708 // function, regardless of Type. Previously re-use of names was okay as
709 // long as they were distinct types. With type planes collapsing because
710 // of the signedness change and because of PR411, this can no longer be
711 // supported. We must search the entire symbol table for a conflicting
712 // name and make the name unique. No warning is needed as this can't
714 std::string NewName = makeNameUnique(Name);
715 // We're changing the name but it will probably be used by other
716 // instructions as operands later on. Consequently we have to retain
717 // a mapping of the renaming that we're doing.
718 RenameMapKey Key = std::make_pair(Name,V->getType());
719 CurFun.RenameMap[Key] = NewName;
728 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
729 /// this is a declaration, otherwise it is a definition.
730 static GlobalVariable *
731 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
732 bool isConstantGlobal, const Type *Ty,
733 Constant *Initializer) {
734 if (isa<FunctionType>(Ty))
735 error("Cannot declare global vars of function type");
737 const PointerType *PTy = PointerType::get(Ty);
741 Name = NameStr; // Copy string
742 free(NameStr); // Free old string
745 // See if this global value was forward referenced. If so, recycle the
749 ID = ValID::create((char*)Name.c_str());
751 ID = ValID::create((int)CurModule.Values[PTy].size());
754 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
755 // Move the global to the end of the list, from whereever it was
756 // previously inserted.
757 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
758 CurModule.CurrentModule->getGlobalList().remove(GV);
759 CurModule.CurrentModule->getGlobalList().push_back(GV);
760 GV->setInitializer(Initializer);
761 GV->setLinkage(Linkage);
762 GV->setConstant(isConstantGlobal);
763 InsertValue(GV, CurModule.Values);
767 // If this global has a name, check to see if there is already a definition
768 // of this global in the module and emit warnings if there are conflicts.
770 // The global has a name. See if there's an existing one of the same name.
771 if (CurModule.CurrentModule->getNamedGlobal(Name)) {
772 // We found an existing global ov the same name. This isn't allowed
773 // in LLVM 2.0. Consequently, we must alter the name of the global so it
774 // can at least compile. This can happen because of type planes
775 // There is alread a global of the same name which means there is a
776 // conflict. Let's see what we can do about it.
777 std::string NewName(makeNameUnique(Name));
778 if (Linkage == GlobalValue::InternalLinkage) {
779 // The linkage type is internal so just warn about the rename without
780 // invoking "scarey language" about linkage failures. GVars with
781 // InternalLinkage can be renamed at will.
782 warning("Global variable '" + Name + "' was renamed to '"+
785 // The linkage of this gval is external so we can't reliably rename
786 // it because it could potentially create a linking problem.
787 // However, we can't leave the name conflict in the output either or
788 // it won't assemble with LLVM 2.0. So, all we can do is rename
789 // this one to something unique and emit a warning about the problem.
790 warning("Renaming global variable '" + Name + "' to '" + NewName +
791 "' may cause linkage errors");
794 // Put the renaming in the global rename map
795 RenameMapKey Key = std::make_pair(Name,PointerType::get(Ty));
796 CurModule.RenameMap[Key] = NewName;
803 // Otherwise there is no existing GV to use, create one now.
805 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
806 CurModule.CurrentModule);
807 InsertValue(GV, CurModule.Values);
811 // setTypeName - Set the specified type to the name given. The name may be
812 // null potentially, in which case this is a noop. The string passed in is
813 // assumed to be a malloc'd string buffer, and is freed by this function.
815 // This function returns true if the type has already been defined, but is
816 // allowed to be redefined in the specified context. If the name is a new name
817 // for the type plane, it is inserted and false is returned.
818 static bool setTypeName(const Type *T, char *NameStr) {
819 assert(!inFunctionScope() && "Can't give types function-local names");
820 if (NameStr == 0) return false;
822 std::string Name(NameStr); // Copy string
823 free(NameStr); // Free old string
825 // We don't allow assigning names to void type
826 if (T == Type::VoidTy) {
827 error("Can't assign name '" + Name + "' to the void type");
831 // Set the type name, checking for conflicts as we do so.
832 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
834 if (AlreadyExists) { // Inserting a name that is already defined???
835 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
836 assert(Existing && "Conflict but no matching type?");
838 // There is only one case where this is allowed: when we are refining an
839 // opaque type. In this case, Existing will be an opaque type.
840 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
841 // We ARE replacing an opaque type!
842 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
846 // Otherwise, this is an attempt to redefine a type. That's okay if
847 // the redefinition is identical to the original. This will be so if
848 // Existing and T point to the same Type object. In this one case we
849 // allow the equivalent redefinition.
850 if (Existing == T) return true; // Yes, it's equal.
852 // Any other kind of (non-equivalent) redefinition is an error.
853 error("Redefinition of type named '" + Name + "' in the '" +
854 T->getDescription() + "' type plane");
860 //===----------------------------------------------------------------------===//
861 // Code for handling upreferences in type names...
864 // TypeContains - Returns true if Ty directly contains E in it.
866 static bool TypeContains(const Type *Ty, const Type *E) {
867 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
868 E) != Ty->subtype_end();
873 // NestingLevel - The number of nesting levels that need to be popped before
874 // this type is resolved.
875 unsigned NestingLevel;
877 // LastContainedTy - This is the type at the current binding level for the
878 // type. Every time we reduce the nesting level, this gets updated.
879 const Type *LastContainedTy;
881 // UpRefTy - This is the actual opaque type that the upreference is
885 UpRefRecord(unsigned NL, OpaqueType *URTy)
886 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
890 // UpRefs - A list of the outstanding upreferences that need to be resolved.
891 static std::vector<UpRefRecord> UpRefs;
893 /// HandleUpRefs - Every time we finish a new layer of types, this function is
894 /// called. It loops through the UpRefs vector, which is a list of the
895 /// currently active types. For each type, if the up reference is contained in
896 /// the newly completed type, we decrement the level count. When the level
897 /// count reaches zero, the upreferenced type is the type that is passed in:
898 /// thus we can complete the cycle.
900 static PATypeHolder HandleUpRefs(const Type *ty) {
901 // If Ty isn't abstract, or if there are no up-references in it, then there is
902 // nothing to resolve here.
903 if (!ty->isAbstract() || UpRefs.empty()) return ty;
906 UR_OUT("Type '" << Ty->getDescription() <<
907 "' newly formed. Resolving upreferences.\n" <<
908 UpRefs.size() << " upreferences active!\n");
910 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
911 // to zero), we resolve them all together before we resolve them to Ty. At
912 // the end of the loop, if there is anything to resolve to Ty, it will be in
914 OpaqueType *TypeToResolve = 0;
916 for (unsigned i = 0; i != UpRefs.size(); ++i) {
917 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
918 << UpRefs[i].second->getDescription() << ") = "
919 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
920 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
921 // Decrement level of upreference
922 unsigned Level = --UpRefs[i].NestingLevel;
923 UpRefs[i].LastContainedTy = Ty;
924 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
925 if (Level == 0) { // Upreference should be resolved!
926 if (!TypeToResolve) {
927 TypeToResolve = UpRefs[i].UpRefTy;
929 UR_OUT(" * Resolving upreference for "
930 << UpRefs[i].second->getDescription() << "\n";
931 std::string OldName = UpRefs[i].UpRefTy->getDescription());
932 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
933 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
934 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
936 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
937 --i; // Do not skip the next element...
943 UR_OUT(" * Resolving upreference for "
944 << UpRefs[i].second->getDescription() << "\n";
945 std::string OldName = TypeToResolve->getDescription());
946 TypeToResolve->refineAbstractTypeTo(Ty);
952 static inline Instruction::TermOps
953 getTermOp(TermOps op) {
955 default : assert(0 && "Invalid OldTermOp");
956 case RetOp : return Instruction::Ret;
957 case BrOp : return Instruction::Br;
958 case SwitchOp : return Instruction::Switch;
959 case InvokeOp : return Instruction::Invoke;
960 case UnwindOp : return Instruction::Unwind;
961 case UnreachableOp: return Instruction::Unreachable;
965 static inline Instruction::BinaryOps
966 getBinaryOp(BinaryOps op, const Type *Ty, Signedness Sign) {
968 default : assert(0 && "Invalid OldBinaryOps");
974 case SetGT : assert(0 && "Should use getCompareOp");
975 case AddOp : return Instruction::Add;
976 case SubOp : return Instruction::Sub;
977 case MulOp : return Instruction::Mul;
979 // This is an obsolete instruction so we must upgrade it based on the
980 // types of its operands.
981 bool isFP = Ty->isFloatingPoint();
982 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
983 // If its a packed type we want to use the element type
984 isFP = PTy->getElementType()->isFloatingPoint();
986 return Instruction::FDiv;
987 else if (Sign == Signed)
988 return Instruction::SDiv;
989 return Instruction::UDiv;
991 case UDivOp : return Instruction::UDiv;
992 case SDivOp : return Instruction::SDiv;
993 case FDivOp : return Instruction::FDiv;
995 // This is an obsolete instruction so we must upgrade it based on the
996 // types of its operands.
997 bool isFP = Ty->isFloatingPoint();
998 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
999 // If its a packed type we want to use the element type
1000 isFP = PTy->getElementType()->isFloatingPoint();
1001 // Select correct opcode
1003 return Instruction::FRem;
1004 else if (Sign == Signed)
1005 return Instruction::SRem;
1006 return Instruction::URem;
1008 case URemOp : return Instruction::URem;
1009 case SRemOp : return Instruction::SRem;
1010 case FRemOp : return Instruction::FRem;
1011 case AndOp : return Instruction::And;
1012 case OrOp : return Instruction::Or;
1013 case XorOp : return Instruction::Xor;
1017 static inline Instruction::OtherOps
1018 getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
1020 bool isSigned = Sign == Signed;
1021 bool isFP = Ty->isFloatingPoint();
1023 default : assert(0 && "Invalid OldSetCC");
1026 predicate = FCmpInst::FCMP_OEQ;
1027 return Instruction::FCmp;
1029 predicate = ICmpInst::ICMP_EQ;
1030 return Instruction::ICmp;
1034 predicate = FCmpInst::FCMP_UNE;
1035 return Instruction::FCmp;
1037 predicate = ICmpInst::ICMP_NE;
1038 return Instruction::ICmp;
1042 predicate = FCmpInst::FCMP_OLE;
1043 return Instruction::FCmp;
1046 predicate = ICmpInst::ICMP_SLE;
1048 predicate = ICmpInst::ICMP_ULE;
1049 return Instruction::ICmp;
1053 predicate = FCmpInst::FCMP_OGE;
1054 return Instruction::FCmp;
1057 predicate = ICmpInst::ICMP_SGE;
1059 predicate = ICmpInst::ICMP_UGE;
1060 return Instruction::ICmp;
1064 predicate = FCmpInst::FCMP_OLT;
1065 return Instruction::FCmp;
1068 predicate = ICmpInst::ICMP_SLT;
1070 predicate = ICmpInst::ICMP_ULT;
1071 return Instruction::ICmp;
1075 predicate = FCmpInst::FCMP_OGT;
1076 return Instruction::FCmp;
1079 predicate = ICmpInst::ICMP_SGT;
1081 predicate = ICmpInst::ICMP_UGT;
1082 return Instruction::ICmp;
1087 static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1089 default : assert(0 && "Invalid OldMemoryOps");
1090 case MallocOp : return Instruction::Malloc;
1091 case FreeOp : return Instruction::Free;
1092 case AllocaOp : return Instruction::Alloca;
1093 case LoadOp : return Instruction::Load;
1094 case StoreOp : return Instruction::Store;
1095 case GetElementPtrOp : return Instruction::GetElementPtr;
1099 static inline Instruction::OtherOps
1100 getOtherOp(OtherOps op, Signedness Sign) {
1102 default : assert(0 && "Invalid OldOtherOps");
1103 case PHIOp : return Instruction::PHI;
1104 case CallOp : return Instruction::Call;
1105 case ShlOp : return Instruction::Shl;
1108 return Instruction::AShr;
1109 return Instruction::LShr;
1110 case SelectOp : return Instruction::Select;
1111 case UserOp1 : return Instruction::UserOp1;
1112 case UserOp2 : return Instruction::UserOp2;
1113 case VAArg : return Instruction::VAArg;
1114 case ExtractElementOp : return Instruction::ExtractElement;
1115 case InsertElementOp : return Instruction::InsertElement;
1116 case ShuffleVectorOp : return Instruction::ShuffleVector;
1117 case ICmpOp : return Instruction::ICmp;
1118 case FCmpOp : return Instruction::FCmp;
1119 case LShrOp : return Instruction::LShr;
1120 case AShrOp : return Instruction::AShr;
1124 static inline Value*
1125 getCast(CastOps op, Value *Src, Signedness SrcSign, const Type *DstTy,
1126 Signedness DstSign, bool ForceInstruction = false) {
1127 Instruction::CastOps Opcode;
1128 const Type* SrcTy = Src->getType();
1130 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1131 // fp -> ptr cast is no longer supported but we must upgrade this
1132 // by doing a double cast: fp -> int -> ptr
1133 SrcTy = Type::Int64Ty;
1134 Opcode = Instruction::IntToPtr;
1135 if (isa<Constant>(Src)) {
1136 Src = ConstantExpr::getCast(Instruction::FPToUI,
1137 cast<Constant>(Src), SrcTy);
1139 std::string NewName(makeNameUnique(Src->getName()));
1140 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1142 } else if (isa<IntegerType>(DstTy) &&
1143 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1144 // cast type %x to bool was previously defined as setne type %x, null
1145 // The cast semantic is now to truncate, not compare so we must retain
1146 // the original intent by replacing the cast with a setne
1147 Constant* Null = Constant::getNullValue(SrcTy);
1148 Instruction::OtherOps Opcode = Instruction::ICmp;
1149 unsigned short predicate = ICmpInst::ICMP_NE;
1150 if (SrcTy->isFloatingPoint()) {
1151 Opcode = Instruction::FCmp;
1152 predicate = FCmpInst::FCMP_ONE;
1153 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1154 error("Invalid cast to bool");
1156 if (isa<Constant>(Src) && !ForceInstruction)
1157 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1159 return CmpInst::create(Opcode, predicate, Src, Null);
1161 // Determine the opcode to use by calling CastInst::getCastOpcode
1163 CastInst::getCastOpcode(Src, SrcSign == Signed, DstTy, DstSign == Signed);
1165 } else switch (op) {
1166 default: assert(0 && "Invalid cast token");
1167 case TruncOp: Opcode = Instruction::Trunc; break;
1168 case ZExtOp: Opcode = Instruction::ZExt; break;
1169 case SExtOp: Opcode = Instruction::SExt; break;
1170 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1171 case FPExtOp: Opcode = Instruction::FPExt; break;
1172 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1173 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1174 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1175 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1176 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1177 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1178 case BitCastOp: Opcode = Instruction::BitCast; break;
1181 if (isa<Constant>(Src) && !ForceInstruction)
1182 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1183 return CastInst::create(Opcode, Src, DstTy);
1186 static Instruction *
1187 upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1188 std::vector<Value*>& Args) {
1190 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1191 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1192 if (Args.size() != 2)
1193 error("Invalid prototype for " + Name + " prototype");
1194 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1196 static unsigned upgradeCount = 1;
1197 const Type* PtrTy = PointerType::get(Type::Int8Ty);
1198 std::vector<const Type*> Params;
1199 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1200 if (Args.size() != 1)
1201 error("Invalid prototype for " + Name + " prototype");
1202 Params.push_back(PtrTy);
1203 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1204 const PointerType *PFTy = PointerType::get(FTy);
1205 Value* Func = getVal(PFTy, ID);
1206 std::string InstName("va_upgrade");
1207 InstName += llvm::utostr(upgradeCount++);
1208 Args[0] = new BitCastInst(Args[0], PtrTy, InstName, CurBB);
1209 return new CallInst(Func, Args);
1210 } else if (Name == "llvm.va_copy") {
1211 if (Args.size() != 2)
1212 error("Invalid prototype for " + Name + " prototype");
1213 Params.push_back(PtrTy);
1214 Params.push_back(PtrTy);
1215 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1216 const PointerType *PFTy = PointerType::get(FTy);
1217 Value* Func = getVal(PFTy, ID);
1218 std::string InstName0("va_upgrade");
1219 InstName0 += llvm::utostr(upgradeCount++);
1220 std::string InstName1("va_upgrade");
1221 InstName1 += llvm::utostr(upgradeCount++);
1222 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1223 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1224 return new CallInst(Func, Args);
1230 const Type* upgradeGEPIndices(const Type* PTy,
1231 std::vector<ValueInfo> *Indices,
1232 std::vector<Value*> &VIndices,
1233 std::vector<Constant*> *CIndices = 0) {
1234 // Traverse the indices with a gep_type_iterator so we can build the list
1235 // of constant and value indices for use later. Also perform upgrades
1237 if (CIndices) CIndices->clear();
1238 for (unsigned i = 0, e = Indices->size(); i != e; ++i)
1239 VIndices.push_back((*Indices)[i].V);
1240 generic_gep_type_iterator<std::vector<Value*>::iterator>
1241 GTI = gep_type_begin(PTy, VIndices.begin(), VIndices.end()),
1242 GTE = gep_type_end(PTy, VIndices.begin(), VIndices.end());
1243 for (unsigned i = 0, e = Indices->size(); i != e && GTI != GTE; ++i, ++GTI) {
1244 Value *Index = VIndices[i];
1245 if (CIndices && !isa<Constant>(Index))
1246 error("Indices to constant getelementptr must be constants");
1247 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1248 // struct indices to i32 struct indices with ZExt for compatibility.
1249 else if (isa<StructType>(*GTI)) { // Only change struct indices
1250 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Index))
1251 if (CUI->getType()->getBitWidth() == 8)
1253 ConstantExpr::getCast(Instruction::ZExt, CUI, Type::Int32Ty);
1255 // Make sure that unsigned SequentialType indices are zext'd to
1256 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1257 // all indices for SequentialType elements. We must retain the same
1258 // semantic (zext) for unsigned types.
1259 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType()))
1260 if (Ity->getBitWidth() < 64 && (*Indices)[i].S == Unsigned) {
1262 Index = ConstantExpr::getCast(Instruction::ZExt,
1263 cast<Constant>(Index), Type::Int64Ty);
1265 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1266 makeNameUnique("gep_upgrade"), CurBB);
1267 VIndices[i] = Index;
1270 // Add to the CIndices list, if requested.
1272 CIndices->push_back(cast<Constant>(Index));
1276 GetElementPtrInst::getIndexedType(PTy, VIndices, true);
1278 error("Index list invalid for constant getelementptr");
1282 unsigned upgradeCallingConv(unsigned CC) {
1284 case OldCallingConv::C : return CallingConv::C;
1285 case OldCallingConv::CSRet : return CallingConv::C;
1286 case OldCallingConv::Fast : return CallingConv::Fast;
1287 case OldCallingConv::Cold : return CallingConv::Cold;
1288 case OldCallingConv::X86_StdCall : return CallingConv::X86_StdCall;
1289 case OldCallingConv::X86_FastCall: return CallingConv::X86_FastCall;
1295 Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1296 bool debug, bool addAttrs)
1299 CurFilename = infile;
1302 AddAttributes = addAttrs;
1303 ObsoleteVarArgs = false;
1306 CurModule.CurrentModule = new Module(CurFilename);
1308 // Check to make sure the parser succeeded
1311 delete ParserResult;
1312 std::cerr << "llvm-upgrade: parse failed.\n";
1316 // Check to make sure that parsing produced a result
1317 if (!ParserResult) {
1318 std::cerr << "llvm-upgrade: no parse result.\n";
1322 // Reset ParserResult variable while saving its value for the result.
1323 Module *Result = ParserResult;
1326 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1329 if ((F = Result->getNamedFunction("llvm.va_start"))
1330 && F->getFunctionType()->getNumParams() == 0)
1331 ObsoleteVarArgs = true;
1332 if((F = Result->getNamedFunction("llvm.va_copy"))
1333 && F->getFunctionType()->getNumParams() == 1)
1334 ObsoleteVarArgs = true;
1337 if (ObsoleteVarArgs && NewVarArgs) {
1338 error("This file is corrupt: it uses both new and old style varargs");
1342 if(ObsoleteVarArgs) {
1343 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
1344 if (F->arg_size() != 0) {
1345 error("Obsolete va_start takes 0 argument");
1351 //bar = alloca typeof(foo)
1355 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1356 const Type* ArgTy = F->getFunctionType()->getReturnType();
1357 const Type* ArgTyPtr = PointerType::get(ArgTy);
1358 Function* NF = cast<Function>(Result->getOrInsertFunction(
1359 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1361 while (!F->use_empty()) {
1362 CallInst* CI = cast<CallInst>(F->use_back());
1363 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1364 new CallInst(NF, bar, "", CI);
1365 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1366 CI->replaceAllUsesWith(foo);
1367 CI->getParent()->getInstList().erase(CI);
1369 Result->getFunctionList().erase(F);
1372 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
1373 if(F->arg_size() != 1) {
1374 error("Obsolete va_end takes 1 argument");
1380 //bar = alloca 1 of typeof(foo)
1382 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1383 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1384 const Type* ArgTyPtr = PointerType::get(ArgTy);
1385 Function* NF = cast<Function>(Result->getOrInsertFunction(
1386 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1388 while (!F->use_empty()) {
1389 CallInst* CI = cast<CallInst>(F->use_back());
1390 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1391 new StoreInst(CI->getOperand(1), bar, CI);
1392 new CallInst(NF, bar, "", CI);
1393 CI->getParent()->getInstList().erase(CI);
1395 Result->getFunctionList().erase(F);
1398 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
1399 if(F->arg_size() != 1) {
1400 error("Obsolete va_copy takes 1 argument");
1405 //a = alloca 1 of typeof(foo)
1406 //b = alloca 1 of typeof(foo)
1411 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1412 const Type* ArgTy = F->getFunctionType()->getReturnType();
1413 const Type* ArgTyPtr = PointerType::get(ArgTy);
1414 Function* NF = cast<Function>(Result->getOrInsertFunction(
1415 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1417 while (!F->use_empty()) {
1418 CallInst* CI = cast<CallInst>(F->use_back());
1419 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1420 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1421 new StoreInst(CI->getOperand(1), b, CI);
1422 new CallInst(NF, a, b, "", CI);
1423 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1424 CI->replaceAllUsesWith(foo);
1425 CI->getParent()->getInstList().erase(CI);
1427 Result->getFunctionList().erase(F);
1434 } // end llvm namespace
1436 using namespace llvm;
1441 llvm::Module *ModuleVal;
1442 llvm::Function *FunctionVal;
1443 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1444 llvm::BasicBlock *BasicBlockVal;
1445 llvm::TerminatorInst *TermInstVal;
1446 llvm::InstrInfo InstVal;
1447 llvm::ConstInfo ConstVal;
1448 llvm::ValueInfo ValueVal;
1449 llvm::PATypeInfo TypeVal;
1450 llvm::TypeInfo PrimType;
1451 llvm::PHIListInfo PHIList;
1452 std::list<llvm::PATypeInfo> *TypeList;
1453 std::vector<llvm::ValueInfo> *ValueList;
1454 std::vector<llvm::ConstInfo> *ConstVector;
1457 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1458 // Represent the RHS of PHI node
1459 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1461 llvm::GlobalValue::LinkageTypes Linkage;
1469 char *StrVal; // This memory is strdup'd!
1470 llvm::ValID ValIDVal; // strdup'd memory maybe!
1472 llvm::BinaryOps BinaryOpVal;
1473 llvm::TermOps TermOpVal;
1474 llvm::MemoryOps MemOpVal;
1475 llvm::OtherOps OtherOpVal;
1476 llvm::CastOps CastOpVal;
1477 llvm::ICmpInst::Predicate IPred;
1478 llvm::FCmpInst::Predicate FPred;
1479 llvm::Module::Endianness Endianness;
1482 %type <ModuleVal> Module FunctionList
1483 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1484 %type <BasicBlockVal> BasicBlock InstructionList
1485 %type <TermInstVal> BBTerminatorInst
1486 %type <InstVal> Inst InstVal MemoryInst
1487 %type <ConstVal> ConstVal ConstExpr
1488 %type <ConstVector> ConstVector
1489 %type <ArgList> ArgList ArgListH
1490 %type <ArgVal> ArgVal
1491 %type <PHIList> PHIList
1492 %type <ValueList> ValueRefList ValueRefListE // For call param lists
1493 %type <ValueList> IndexList // For GEP derived indices
1494 %type <TypeList> TypeListI ArgTypeListI
1495 %type <JumpTable> JumpTable
1496 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1497 %type <BoolVal> OptVolatile // 'volatile' or not
1498 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1499 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1500 %type <Linkage> OptLinkage
1501 %type <Endianness> BigOrLittle
1503 // ValueRef - Unresolved reference to a definition or BB
1504 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1505 %type <ValueVal> ResolvedVal // <type> <valref> pair
1507 // Tokens and types for handling constant integer values
1509 // ESINT64VAL - A negative number within long long range
1510 %token <SInt64Val> ESINT64VAL
1512 // EUINT64VAL - A positive number within uns. long long range
1513 %token <UInt64Val> EUINT64VAL
1514 %type <SInt64Val> EINT64VAL
1516 %token <SIntVal> SINTVAL // Signed 32 bit ints...
1517 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1518 %type <SIntVal> INTVAL
1519 %token <FPVal> FPVAL // Float or Double constant
1521 // Built in types...
1522 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
1523 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1524 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1525 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1527 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1528 %type <StrVal> Name OptName OptAssign
1529 %type <UIntVal> OptAlign OptCAlign
1530 %type <StrVal> OptSection SectionString
1532 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1533 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1534 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1535 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1536 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1537 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1538 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1539 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1541 %type <UIntVal> OptCallingConv
1543 // Basic Block Terminating Operators
1544 %token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1545 %token UNWIND EXCEPT
1548 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1549 %token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
1550 %token <BinaryOpVal> AND OR XOR
1551 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1552 %token <OtherOpVal> ICMP FCMP
1554 // Memory Instructions
1555 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1558 %type <OtherOpVal> ShiftOps
1559 %token <OtherOpVal> PHI_TOK SELECT SHL SHR ASHR LSHR VAARG
1560 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1561 %token VAARG_old VANEXT_old //OBSOLETE
1563 // Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
1564 %type <IPred> IPredicates
1565 %type <FPred> FPredicates
1566 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1567 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1569 %token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1570 %token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1571 %type <CastOpVal> CastOps
1577 // Handle constant integer size restriction and conversion...
1582 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1583 error("Value too large for type");
1589 : ESINT64VAL // These have same type and can't cause problems...
1591 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1592 error("Value too large for type");
1596 // Operations that are notably excluded from this list include:
1597 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1600 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1608 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1612 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1613 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1614 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1615 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1616 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1620 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1621 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1622 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1623 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1624 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1625 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1626 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1627 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1628 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1631 : SHL | SHR | ASHR | LSHR
1635 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1636 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1639 // These are some types that allow classification if we only want a particular
1640 // thing... for example, only a signed, unsigned, or integral type.
1642 : LONG | INT | SHORT | SBYTE
1646 : ULONG | UINT | USHORT | UBYTE
1650 : SIntType | UIntType
1657 // OptAssign - Value producing statements have an optional assignment component
1667 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1668 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1669 | WEAK { $$ = GlobalValue::WeakLinkage; }
1670 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1671 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1672 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1673 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1674 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1678 : /*empty*/ { CurFun.LastCC = $$ = OldCallingConv::C; }
1679 | CCC_TOK { CurFun.LastCC = $$ = OldCallingConv::C; }
1680 | CSRETCC_TOK { CurFun.LastCC = $$ = OldCallingConv::CSRet; }
1681 | FASTCC_TOK { CurFun.LastCC = $$ = OldCallingConv::Fast; }
1682 | COLDCC_TOK { CurFun.LastCC = $$ = OldCallingConv::Cold; }
1683 | X86_STDCALLCC_TOK { CurFun.LastCC = $$ = OldCallingConv::X86_StdCall; }
1684 | X86_FASTCALLCC_TOK { CurFun.LastCC = $$ = OldCallingConv::X86_FastCall; }
1685 | CC_TOK EUINT64VAL {
1686 if ((unsigned)$2 != $2)
1687 error("Calling conv too large");
1692 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1693 // a comma before it.
1695 : /*empty*/ { $$ = 0; }
1696 | ALIGN EUINT64VAL {
1698 if ($$ != 0 && !isPowerOf2_32($$))
1699 error("Alignment must be a power of two");
1704 : /*empty*/ { $$ = 0; }
1705 | ',' ALIGN EUINT64VAL {
1707 if ($$ != 0 && !isPowerOf2_32($$))
1708 error("Alignment must be a power of two");
1713 : SECTION STRINGCONSTANT {
1714 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1715 if ($2[i] == '"' || $2[i] == '\\')
1716 error("Invalid character in section name");
1722 : /*empty*/ { $$ = 0; }
1723 | SectionString { $$ = $1; }
1726 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1727 // is set to be the global we are processing.
1731 | ',' GlobalVarAttribute GlobalVarAttributes {}
1736 CurGV->setSection($1);
1739 | ALIGN EUINT64VAL {
1740 if ($2 != 0 && !isPowerOf2_32($2))
1741 error("Alignment must be a power of two");
1742 CurGV->setAlignment($2);
1747 //===----------------------------------------------------------------------===//
1748 // Types includes all predefined types... except void, because it can only be
1749 // used in specific contexts (function returning void for example). To have
1750 // access to it, a user must explicitly use TypesV.
1753 // TypesV includes all of 'Types', but it also includes the void type.
1757 $$.T = new PATypeHolder($1.T);
1765 $$.T = new PATypeHolder($1.T);
1772 if (!UpRefs.empty())
1773 error("Invalid upreference in type: " + (*$1.T)->getDescription());
1779 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
1780 | LONG | ULONG | FLOAT | DOUBLE | LABEL
1783 // Derived types are added later...
1786 $$.T = new PATypeHolder($1.T);
1790 $$.T = new PATypeHolder(OpaqueType::get());
1793 | SymbolicValueRef { // Named types are also simple types...
1794 const Type* tmp = getType($1);
1795 $$.T = new PATypeHolder(tmp);
1796 $$.S = Signless; // FIXME: what if its signed?
1798 | '\\' EUINT64VAL { // Type UpReference
1799 if ($2 > (uint64_t)~0U)
1800 error("Value out of range");
1801 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1802 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1803 $$.T = new PATypeHolder(OT);
1805 UR_OUT("New Upreference!\n");
1807 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1808 std::vector<const Type*> Params;
1809 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1810 E = $3->end(); I != E; ++I) {
1811 Params.push_back(I->T->get());
1814 FunctionType::ParamAttrsList ParamAttrs;
1815 if (CurFun.LastCC == OldCallingConv::CSRet) {
1816 ParamAttrs.push_back(FunctionType::NoAttributeSet);
1817 ParamAttrs.push_back(FunctionType::StructRetAttribute);
1819 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1820 if (isVarArg) Params.pop_back();
1822 $$.T = new PATypeHolder(
1823 HandleUpRefs(FunctionType::get($1.T->get(),Params,isVarArg, ParamAttrs)));
1825 delete $1.T; // Delete the return type handle
1826 delete $3; // Delete the argument list
1828 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1829 $$.T = new PATypeHolder(HandleUpRefs(ArrayType::get($4.T->get(),
1834 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1835 const llvm::Type* ElemTy = $4.T->get();
1836 if ((unsigned)$2 != $2)
1837 error("Unsigned result not equal to signed result");
1838 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
1839 error("Elements of a PackedType must be integer or floating point");
1840 if (!isPowerOf2_32($2))
1841 error("PackedType length should be a power of 2");
1842 $$.T = new PATypeHolder(HandleUpRefs(PackedType::get(ElemTy,
1847 | '{' TypeListI '}' { // Structure type?
1848 std::vector<const Type*> Elements;
1849 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
1850 E = $2->end(); I != E; ++I)
1851 Elements.push_back(I->T->get());
1852 $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1856 | '{' '}' { // Empty structure type?
1857 $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1860 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
1861 std::vector<const Type*> Elements;
1862 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1863 E = $3->end(); I != E; ++I) {
1864 Elements.push_back(I->T->get());
1867 $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1871 | '<' '{' '}' '>' { // Empty packed structure type?
1872 $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
1875 | UpRTypes '*' { // Pointer type?
1876 if ($1.T->get() == Type::LabelTy)
1877 error("Cannot form a pointer to a basic block");
1878 $$.T = new PATypeHolder(HandleUpRefs(PointerType::get($1.T->get())));
1884 // TypeList - Used for struct declarations and as a basis for function type
1885 // declaration type lists
1889 $$ = new std::list<PATypeInfo>();
1892 | TypeListI ',' UpRTypes {
1893 ($$=$1)->push_back($3);
1897 // ArgTypeList - List of types for a function type declaration...
1900 | TypeListI ',' DOTDOTDOT {
1902 VoidTI.T = new PATypeHolder(Type::VoidTy);
1903 VoidTI.S = Signless;
1904 ($$=$1)->push_back(VoidTI);
1907 $$ = new std::list<PATypeInfo>();
1909 VoidTI.T = new PATypeHolder(Type::VoidTy);
1910 VoidTI.S = Signless;
1911 $$->push_back(VoidTI);
1914 $$ = new std::list<PATypeInfo>();
1918 // ConstVal - The various declarations that go into the constant pool. This
1919 // production is used ONLY to represent constants that show up AFTER a 'const',
1920 // 'constant' or 'global' token at global scope. Constants that can be inlined
1921 // into other expressions (such as integers and constexprs) are handled by the
1922 // ResolvedVal, ValueRef and ConstValueRef productions.
1925 : Types '[' ConstVector ']' { // Nonempty unsized arr
1926 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1928 error("Cannot make array constant with type: '" +
1929 $1.T->get()->getDescription() + "'");
1930 const Type *ETy = ATy->getElementType();
1931 int NumElements = ATy->getNumElements();
1933 // Verify that we have the correct size...
1934 if (NumElements != -1 && NumElements != (int)$3->size())
1935 error("Type mismatch: constant sized array initialized with " +
1936 utostr($3->size()) + " arguments, but has size of " +
1937 itostr(NumElements) + "");
1939 // Verify all elements are correct type!
1940 std::vector<Constant*> Elems;
1941 for (unsigned i = 0; i < $3->size(); i++) {
1942 Constant *C = (*$3)[i].C;
1943 const Type* ValTy = C->getType();
1945 error("Element #" + utostr(i) + " is not of type '" +
1946 ETy->getDescription() +"' as required!\nIt is of type '"+
1947 ValTy->getDescription() + "'");
1950 $$.C = ConstantArray::get(ATy, Elems);
1956 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1958 error("Cannot make array constant with type: '" +
1959 $1.T->get()->getDescription() + "'");
1960 int NumElements = ATy->getNumElements();
1961 if (NumElements != -1 && NumElements != 0)
1962 error("Type mismatch: constant sized array initialized with 0"
1963 " arguments, but has size of " + itostr(NumElements) +"");
1964 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
1968 | Types 'c' STRINGCONSTANT {
1969 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1971 error("Cannot make array constant with type: '" +
1972 $1.T->get()->getDescription() + "'");
1973 int NumElements = ATy->getNumElements();
1974 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
1975 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
1976 error("String arrays require type i8, not '" + ETy->getDescription() +
1978 char *EndStr = UnEscapeLexed($3, true);
1979 if (NumElements != -1 && NumElements != (EndStr-$3))
1980 error("Can't build string constant of size " +
1981 itostr((int)(EndStr-$3)) + " when array has size " +
1982 itostr(NumElements) + "");
1983 std::vector<Constant*> Vals;
1984 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
1985 Vals.push_back(ConstantInt::get(ETy, *C));
1987 $$.C = ConstantArray::get(ATy, Vals);
1991 | Types '<' ConstVector '>' { // Nonempty unsized arr
1992 const PackedType *PTy = dyn_cast<PackedType>($1.T->get());
1994 error("Cannot make packed constant with type: '" +
1995 $1.T->get()->getDescription() + "'");
1996 const Type *ETy = PTy->getElementType();
1997 int NumElements = PTy->getNumElements();
1998 // Verify that we have the correct size...
1999 if (NumElements != -1 && NumElements != (int)$3->size())
2000 error("Type mismatch: constant sized packed initialized with " +
2001 utostr($3->size()) + " arguments, but has size of " +
2002 itostr(NumElements) + "");
2003 // Verify all elements are correct type!
2004 std::vector<Constant*> Elems;
2005 for (unsigned i = 0; i < $3->size(); i++) {
2006 Constant *C = (*$3)[i].C;
2007 const Type* ValTy = C->getType();
2009 error("Element #" + utostr(i) + " is not of type '" +
2010 ETy->getDescription() +"' as required!\nIt is of type '"+
2011 ValTy->getDescription() + "'");
2014 $$.C = ConstantPacked::get(PTy, Elems);
2019 | Types '{' ConstVector '}' {
2020 const StructType *STy = dyn_cast<StructType>($1.T->get());
2022 error("Cannot make struct constant with type: '" +
2023 $1.T->get()->getDescription() + "'");
2024 if ($3->size() != STy->getNumContainedTypes())
2025 error("Illegal number of initializers for structure type");
2027 // Check to ensure that constants are compatible with the type initializer!
2028 std::vector<Constant*> Fields;
2029 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
2030 Constant *C = (*$3)[i].C;
2031 if (C->getType() != STy->getElementType(i))
2032 error("Expected type '" + STy->getElementType(i)->getDescription() +
2033 "' for element #" + utostr(i) + " of structure initializer");
2034 Fields.push_back(C);
2036 $$.C = ConstantStruct::get(STy, Fields);
2042 const StructType *STy = dyn_cast<StructType>($1.T->get());
2044 error("Cannot make struct constant with type: '" +
2045 $1.T->get()->getDescription() + "'");
2046 if (STy->getNumContainedTypes() != 0)
2047 error("Illegal number of initializers for structure type");
2048 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2052 | Types '<' '{' ConstVector '}' '>' {
2053 const StructType *STy = dyn_cast<StructType>($1.T->get());
2055 error("Cannot make packed struct constant with type: '" +
2056 $1.T->get()->getDescription() + "'");
2057 if ($4->size() != STy->getNumContainedTypes())
2058 error("Illegal number of initializers for packed structure type");
2060 // Check to ensure that constants are compatible with the type initializer!
2061 std::vector<Constant*> Fields;
2062 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2063 Constant *C = (*$4)[i].C;
2064 if (C->getType() != STy->getElementType(i))
2065 error("Expected type '" + STy->getElementType(i)->getDescription() +
2066 "' for element #" + utostr(i) + " of packed struct initializer");
2067 Fields.push_back(C);
2069 $$.C = ConstantStruct::get(STy, Fields);
2074 | Types '<' '{' '}' '>' {
2075 const StructType *STy = dyn_cast<StructType>($1.T->get());
2077 error("Cannot make packed struct constant with type: '" +
2078 $1.T->get()->getDescription() + "'");
2079 if (STy->getNumContainedTypes() != 0)
2080 error("Illegal number of initializers for packed structure type");
2081 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2086 const PointerType *PTy = dyn_cast<PointerType>($1.T->get());
2088 error("Cannot make null pointer constant with type: '" +
2089 $1.T->get()->getDescription() + "'");
2090 $$.C = ConstantPointerNull::get(PTy);
2095 $$.C = UndefValue::get($1.T->get());
2099 | Types SymbolicValueRef {
2100 const PointerType *Ty = dyn_cast<PointerType>($1.T->get());
2102 error("Global const reference must be a pointer type, not" +
2103 $1.T->get()->getDescription());
2105 // ConstExprs can exist in the body of a function, thus creating
2106 // GlobalValues whenever they refer to a variable. Because we are in
2107 // the context of a function, getExistingValue will search the functions
2108 // symbol table instead of the module symbol table for the global symbol,
2109 // which throws things all off. To get around this, we just tell
2110 // getExistingValue that we are at global scope here.
2112 Function *SavedCurFn = CurFun.CurrentFunction;
2113 CurFun.CurrentFunction = 0;
2114 Value *V = getExistingValue(Ty, $2);
2115 CurFun.CurrentFunction = SavedCurFn;
2117 // If this is an initializer for a constant pointer, which is referencing a
2118 // (currently) undefined variable, create a stub now that shall be replaced
2119 // in the future with the right type of variable.
2122 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2123 const PointerType *PT = cast<PointerType>(Ty);
2125 // First check to see if the forward references value is already created!
2126 PerModuleInfo::GlobalRefsType::iterator I =
2127 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2129 if (I != CurModule.GlobalRefs.end()) {
2130 V = I->second; // Placeholder already exists, use it...
2134 if ($2.Type == ValID::NameVal) Name = $2.Name;
2136 // Create the forward referenced global.
2138 if (const FunctionType *FTy =
2139 dyn_cast<FunctionType>(PT->getElementType())) {
2140 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2141 CurModule.CurrentModule);
2143 GV = new GlobalVariable(PT->getElementType(), false,
2144 GlobalValue::ExternalLinkage, 0,
2145 Name, CurModule.CurrentModule);
2148 // Keep track of the fact that we have a forward ref to recycle it
2149 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2153 $$.C = cast<GlobalValue>(V);
2155 delete $1.T; // Free the type handle
2158 if ($1.T->get() != $2.C->getType())
2159 error("Mismatched types for constant expression");
2164 | Types ZEROINITIALIZER {
2165 const Type *Ty = $1.T->get();
2166 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2167 error("Cannot create a null initialized value of this type");
2168 $$.C = Constant::getNullValue(Ty);
2172 | SIntType EINT64VAL { // integral constants
2173 const Type *Ty = $1.T;
2174 if (!ConstantInt::isValueValidForType(Ty, $2))
2175 error("Constant value doesn't fit in type");
2176 $$.C = ConstantInt::get(Ty, $2);
2179 | UIntType EUINT64VAL { // integral constants
2180 const Type *Ty = $1.T;
2181 if (!ConstantInt::isValueValidForType(Ty, $2))
2182 error("Constant value doesn't fit in type");
2183 $$.C = ConstantInt::get(Ty, $2);
2186 | BOOL TRUETOK { // Boolean constants
2187 $$.C = ConstantInt::get(Type::Int1Ty, true);
2190 | BOOL FALSETOK { // Boolean constants
2191 $$.C = ConstantInt::get(Type::Int1Ty, false);
2194 | FPType FPVAL { // Float & Double constants
2195 if (!ConstantFP::isValueValidForType($1.T, $2))
2196 error("Floating point constant invalid for type");
2197 $$.C = ConstantFP::get($1.T, $2);
2203 : CastOps '(' ConstVal TO Types ')' {
2204 const Type* SrcTy = $3.C->getType();
2205 const Type* DstTy = $5.T->get();
2206 Signedness SrcSign = $3.S;
2207 Signedness DstSign = $5.S;
2208 if (!SrcTy->isFirstClassType())
2209 error("cast constant expression from a non-primitive type: '" +
2210 SrcTy->getDescription() + "'");
2211 if (!DstTy->isFirstClassType())
2212 error("cast constant expression to a non-primitive type: '" +
2213 DstTy->getDescription() + "'");
2214 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2218 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2219 const Type *Ty = $3.C->getType();
2220 if (!isa<PointerType>(Ty))
2221 error("GetElementPtr requires a pointer operand");
2223 std::vector<Value*> VIndices;
2224 std::vector<Constant*> CIndices;
2225 upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2228 $$.C = ConstantExpr::getGetElementPtr($3.C, CIndices);
2231 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2232 if (!$3.C->getType()->isInteger() ||
2233 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2234 error("Select condition must be bool type");
2235 if ($5.C->getType() != $7.C->getType())
2236 error("Select operand types must match");
2237 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2240 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2241 const Type *Ty = $3.C->getType();
2242 if (Ty != $5.C->getType())
2243 error("Binary operator types must match");
2244 // First, make sure we're dealing with the right opcode by upgrading from
2245 // obsolete versions.
2246 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2248 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2249 // To retain backward compatibility with these early compilers, we emit a
2250 // cast to the appropriate integer type automatically if we are in the
2251 // broken case. See PR424 for more information.
2252 if (!isa<PointerType>(Ty)) {
2253 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2255 const Type *IntPtrTy = 0;
2256 switch (CurModule.CurrentModule->getPointerSize()) {
2257 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2258 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2259 default: error("invalid pointer binary constant expr");
2261 $$.C = ConstantExpr::get(Opcode,
2262 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2263 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2264 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2268 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2269 const Type* Ty = $3.C->getType();
2270 if (Ty != $5.C->getType())
2271 error("Logical operator types must match");
2272 if (!Ty->isInteger()) {
2273 if (!isa<PackedType>(Ty) ||
2274 !cast<PackedType>(Ty)->getElementType()->isInteger())
2275 error("Logical operator requires integer operands");
2277 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2278 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2281 | SetCondOps '(' ConstVal ',' ConstVal ')' {
2282 const Type* Ty = $3.C->getType();
2283 if (Ty != $5.C->getType())
2284 error("setcc operand types must match");
2285 unsigned short pred;
2286 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2287 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2290 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2291 if ($4.C->getType() != $6.C->getType())
2292 error("icmp operand types must match");
2293 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2296 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2297 if ($4.C->getType() != $6.C->getType())
2298 error("fcmp operand types must match");
2299 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2302 | ShiftOps '(' ConstVal ',' ConstVal ')' {
2303 if (!$5.C->getType()->isInteger() ||
2304 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2305 error("Shift count for shift constant must be unsigned byte");
2306 if (!$3.C->getType()->isInteger())
2307 error("Shift constant expression requires integer operand");
2308 $$.C = ConstantExpr::get(getOtherOp($1, $3.S), $3.C, $5.C);
2311 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2312 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2313 error("Invalid extractelement operands");
2314 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2317 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2318 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2319 error("Invalid insertelement operands");
2320 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2323 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2324 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2325 error("Invalid shufflevector operands");
2326 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2332 // ConstVector - A list of comma separated constants.
2334 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2336 $$ = new std::vector<ConstInfo>();
2342 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2344 : GLOBAL { $$ = false; }
2345 | CONSTANT { $$ = true; }
2349 //===----------------------------------------------------------------------===//
2350 // Rules to match Modules
2351 //===----------------------------------------------------------------------===//
2353 // Module rule: Capture the result of parsing the whole file into a result
2358 $$ = ParserResult = $1;
2359 CurModule.ModuleDone();
2363 // FunctionList - A list of functions, preceeded by a constant pool.
2366 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2367 | FunctionList FunctionProto { $$ = $1; }
2368 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2369 | FunctionList IMPLEMENTATION { $$ = $1; }
2371 $$ = CurModule.CurrentModule;
2372 // Emit an error if there are any unresolved types left.
2373 if (!CurModule.LateResolveTypes.empty()) {
2374 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2375 if (DID.Type == ValID::NameVal) {
2376 error("Reference to an undefined type: '"+DID.getName() + "'");
2378 error("Reference to an undefined type: #" + itostr(DID.Num));
2384 // ConstPool - Constants with optional names assigned to them.
2386 : ConstPool OptAssign TYPE TypesV {
2387 // Eagerly resolve types. This is not an optimization, this is a
2388 // requirement that is due to the fact that we could have this:
2390 // %list = type { %list * }
2391 // %list = type { %list * } ; repeated type decl
2393 // If types are not resolved eagerly, then the two types will not be
2394 // determined to be the same type!
2396 const Type* Ty = $4.T->get();
2397 ResolveTypeTo($2, Ty);
2399 if (!setTypeName(Ty, $2) && !$2) {
2400 // If this is a named type that is not a redefinition, add it to the slot
2402 CurModule.Types.push_back(Ty);
2406 | ConstPool FunctionProto { // Function prototypes can be in const pool
2408 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
2410 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2412 error("Global value initializer is not a constant");
2413 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C);
2414 } GlobalVarAttributes {
2417 | ConstPool OptAssign EXTERNAL GlobalType Types {
2418 const Type *Ty = $5.T->get();
2419 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0);
2421 } GlobalVarAttributes {
2424 | ConstPool OptAssign DLLIMPORT GlobalType Types {
2425 const Type *Ty = $5.T->get();
2426 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0);
2428 } GlobalVarAttributes {
2431 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2432 const Type *Ty = $5.T->get();
2434 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0);
2436 } GlobalVarAttributes {
2439 | ConstPool TARGET TargetDefinition {
2441 | ConstPool DEPLIBS '=' LibrariesDefinition {
2443 | /* empty: end of list */ {
2449 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2450 char *EndStr = UnEscapeLexed($1, true);
2451 std::string NewAsm($1, EndStr);
2454 if (AsmSoFar.empty())
2455 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2457 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2462 : BIG { $$ = Module::BigEndian; }
2463 | LITTLE { $$ = Module::LittleEndian; }
2467 : ENDIAN '=' BigOrLittle {
2468 CurModule.setEndianness($3);
2470 | POINTERSIZE '=' EUINT64VAL {
2472 CurModule.setPointerSize(Module::Pointer32);
2474 CurModule.setPointerSize(Module::Pointer64);
2476 error("Invalid pointer size: '" + utostr($3) + "'");
2478 | TRIPLE '=' STRINGCONSTANT {
2479 CurModule.CurrentModule->setTargetTriple($3);
2482 | DATALAYOUT '=' STRINGCONSTANT {
2483 CurModule.CurrentModule->setDataLayout($3);
2493 : LibList ',' STRINGCONSTANT {
2494 CurModule.CurrentModule->addLibrary($3);
2498 CurModule.CurrentModule->addLibrary($1);
2501 | /* empty: end of list */ { }
2504 //===----------------------------------------------------------------------===//
2505 // Rules to match Function Headers
2506 //===----------------------------------------------------------------------===//
2509 : VAR_ID | STRINGCONSTANT
2514 | /*empty*/ { $$ = 0; }
2519 if ($1.T->get() == Type::VoidTy)
2520 error("void typed arguments are invalid");
2521 $$ = new std::pair<PATypeInfo, char*>($1, $2);
2526 : ArgListH ',' ArgVal {
2532 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2539 : ArgListH { $$ = $1; }
2540 | ArgListH ',' DOTDOTDOT {
2543 VoidTI.T = new PATypeHolder(Type::VoidTy);
2544 VoidTI.S = Signless;
2545 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2548 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2550 VoidTI.T = new PATypeHolder(Type::VoidTy);
2551 VoidTI.S = Signless;
2552 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2554 | /* empty */ { $$ = 0; }
2558 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2560 std::string FunctionName($3);
2561 free($3); // Free strdup'd memory!
2563 const Type* RetTy = $2.T->get();
2565 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2566 error("LLVM functions cannot return aggregate types");
2568 std::vector<const Type*> ParamTypeList;
2570 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2571 // i8*. We check here for those names and override the parameter list
2572 // types to ensure the prototype is correct.
2573 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2574 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2575 } else if (FunctionName == "llvm.va_copy") {
2576 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2577 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2578 } else if ($5) { // If there are arguments...
2579 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2580 I = $5->begin(), E = $5->end(); I != E; ++I) {
2581 const Type *Ty = I->first.T->get();
2582 ParamTypeList.push_back(Ty);
2587 ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2588 if (isVarArg) ParamTypeList.pop_back();
2590 // Convert the CSRet calling convention into the corresponding parameter
2592 FunctionType::ParamAttrsList ParamAttrs;
2593 if ($1 == OldCallingConv::CSRet) {
2594 ParamAttrs.push_back(FunctionType::NoAttributeSet); // result
2595 ParamAttrs.push_back(FunctionType::StructRetAttribute); // first arg
2598 const FunctionType *FT = FunctionType::get(RetTy, ParamTypeList, isVarArg,
2600 const PointerType *PFT = PointerType::get(FT);
2604 if (!FunctionName.empty()) {
2605 ID = ValID::create((char*)FunctionName.c_str());
2607 ID = ValID::create((int)CurModule.Values[PFT].size());
2611 // See if this function was forward referenced. If so, recycle the object.
2612 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2613 // Move the function to the end of the list, from whereever it was
2614 // previously inserted.
2615 Fn = cast<Function>(FWRef);
2616 CurModule.CurrentModule->getFunctionList().remove(Fn);
2617 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2618 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2619 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2620 // If this is the case, either we need to be a forward decl, or it needs
2622 if (!CurFun.isDeclare && !Fn->isExternal())
2623 error("Redefinition of function '" + FunctionName + "'");
2625 // Make sure to strip off any argument names so we can't get conflicts.
2626 if (Fn->isExternal())
2627 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2630 } else { // Not already defined?
2631 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2632 CurModule.CurrentModule);
2634 InsertValue(Fn, CurModule.Values);
2637 CurFun.FunctionStart(Fn);
2639 if (CurFun.isDeclare) {
2640 // If we have declaration, always overwrite linkage. This will allow us
2641 // to correctly handle cases, when pointer to function is passed as
2642 // argument to another function.
2643 Fn->setLinkage(CurFun.Linkage);
2645 Fn->setCallingConv(upgradeCallingConv($1));
2646 Fn->setAlignment($8);
2652 // Add all of the arguments we parsed to the function...
2653 if ($5) { // Is null if empty...
2654 if (isVarArg) { // Nuke the last entry
2655 assert($5->back().first.T->get() == Type::VoidTy &&
2656 $5->back().second == 0 && "Not a varargs marker");
2657 delete $5->back().first.T;
2658 $5->pop_back(); // Delete the last entry
2660 Function::arg_iterator ArgIt = Fn->arg_begin();
2661 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2662 I = $5->begin(), E = $5->end(); I != E; ++I, ++ArgIt) {
2663 delete I->first.T; // Delete the typeholder...
2664 setValueName(ArgIt, I->second); // Insert arg into symtab...
2667 delete $5; // We're now done with the argument list
2673 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
2677 : OptLinkage FunctionHeaderH BEGIN {
2678 $$ = CurFun.CurrentFunction;
2680 // Make sure that we keep track of the linkage type even if there was a
2681 // previous "declare".
2687 : ENDTOK | '}' // Allow end of '}' to end a function
2691 : BasicBlockList END {
2697 | DLLIMPORT { CurFun.Linkage = GlobalValue::DLLImportLinkage; }
2698 | EXTERN_WEAK { CurFun.Linkage = GlobalValue::ExternalWeakLinkage; }
2702 : DECLARE { CurFun.isDeclare = true; } FnDeclareLinkage FunctionHeaderH {
2703 $$ = CurFun.CurrentFunction;
2704 CurFun.FunctionDone();
2709 //===----------------------------------------------------------------------===//
2710 // Rules to match Basic Blocks
2711 //===----------------------------------------------------------------------===//
2714 : /* empty */ { $$ = false; }
2715 | SIDEEFFECT { $$ = true; }
2719 // A reference to a direct constant
2720 : ESINT64VAL { $$ = ValID::create($1); }
2721 | EUINT64VAL { $$ = ValID::create($1); }
2722 | FPVAL { $$ = ValID::create($1); }
2723 | TRUETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true)); }
2724 | FALSETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false)); }
2725 | NULL_TOK { $$ = ValID::createNull(); }
2726 | UNDEF { $$ = ValID::createUndef(); }
2727 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
2728 | '<' ConstVector '>' { // Nonempty unsized packed vector
2729 const Type *ETy = (*$2)[0].C->getType();
2730 int NumElements = $2->size();
2731 PackedType* pt = PackedType::get(ETy, NumElements);
2732 PATypeHolder* PTy = new PATypeHolder(
2733 HandleUpRefs(PackedType::get(ETy, NumElements)));
2735 // Verify all elements are correct type!
2736 std::vector<Constant*> Elems;
2737 for (unsigned i = 0; i < $2->size(); i++) {
2738 Constant *C = (*$2)[i].C;
2739 const Type *CTy = C->getType();
2741 error("Element #" + utostr(i) + " is not of type '" +
2742 ETy->getDescription() +"' as required!\nIt is of type '" +
2743 CTy->getDescription() + "'");
2746 $$ = ValID::create(ConstantPacked::get(pt, Elems));
2747 delete PTy; delete $2;
2750 $$ = ValID::create($1.C);
2752 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2753 char *End = UnEscapeLexed($3, true);
2754 std::string AsmStr = std::string($3, End);
2755 End = UnEscapeLexed($5, true);
2756 std::string Constraints = std::string($5, End);
2757 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2763 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2767 : INTVAL { $$ = ValID::create($1); }
2768 | Name { $$ = ValID::create($1); }
2771 // ValueRef - A reference to a definition... either constant or symbolic
2773 : SymbolicValueRef | ConstValueRef
2777 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2778 // type immediately preceeds the value reference, and allows complex constant
2779 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2782 const Type *Ty = $1.T->get();
2784 $$.V = getVal(Ty, $2);
2790 : BasicBlockList BasicBlock {
2793 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2798 // Basic blocks are terminated by branching instructions:
2799 // br, br/cc, switch, ret
2802 : InstructionList OptAssign BBTerminatorInst {
2803 setValueName($3, $2);
2805 $1->getInstList().push_back($3);
2812 : InstructionList Inst {
2814 $1->getInstList().push_back($2.I);
2818 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2819 // Make sure to move the basic block to the correct location in the
2820 // function, instead of leaving it inserted wherever it was first
2822 Function::BasicBlockListType &BBL =
2823 CurFun.CurrentFunction->getBasicBlockList();
2824 BBL.splice(BBL.end(), BBL, $$);
2827 $$ = CurBB = getBBVal(ValID::create($1), true);
2828 // Make sure to move the basic block to the correct location in the
2829 // function, instead of leaving it inserted wherever it was first
2831 Function::BasicBlockListType &BBL =
2832 CurFun.CurrentFunction->getBasicBlockList();
2833 BBL.splice(BBL.end(), BBL, $$);
2837 Unwind : UNWIND | EXCEPT;
2840 : RET ResolvedVal { // Return with a result...
2841 $$ = new ReturnInst($2.V);
2843 | RET VOID { // Return with no result...
2844 $$ = new ReturnInst();
2846 | BR LABEL ValueRef { // Unconditional Branch...
2847 BasicBlock* tmpBB = getBBVal($3);
2848 $$ = new BranchInst(tmpBB);
2849 } // Conditional Branch...
2850 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2851 BasicBlock* tmpBBA = getBBVal($6);
2852 BasicBlock* tmpBBB = getBBVal($9);
2853 Value* tmpVal = getVal(Type::Int1Ty, $3);
2854 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2856 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2857 Value* tmpVal = getVal($2.T, $3);
2858 BasicBlock* tmpBB = getBBVal($6);
2859 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2861 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2863 for (; I != E; ++I) {
2864 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2865 S->addCase(CI, I->second);
2867 error("Switch case is constant, but not a simple integer");
2871 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2872 Value* tmpVal = getVal($2.T, $3);
2873 BasicBlock* tmpBB = getBBVal($6);
2874 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2877 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2878 TO LABEL ValueRef Unwind LABEL ValueRef {
2879 const PointerType *PFTy;
2880 const FunctionType *Ty;
2882 if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
2883 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2884 // Pull out the types of all of the arguments...
2885 std::vector<const Type*> ParamTypes;
2887 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
2889 ParamTypes.push_back((*I).V->getType());
2891 FunctionType::ParamAttrsList ParamAttrs;
2892 if ($2 == OldCallingConv::CSRet) {
2893 ParamAttrs.push_back(FunctionType::NoAttributeSet);
2894 ParamAttrs.push_back(FunctionType::StructRetAttribute);
2896 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2897 if (isVarArg) ParamTypes.pop_back();
2898 Ty = FunctionType::get($3.T->get(), ParamTypes, isVarArg, ParamAttrs);
2899 PFTy = PointerType::get(Ty);
2901 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2902 BasicBlock *Normal = getBBVal($10);
2903 BasicBlock *Except = getBBVal($13);
2905 // Create the call node...
2906 if (!$6) { // Has no arguments?
2907 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2908 } else { // Has arguments?
2909 // Loop through FunctionType's arguments and ensure they are specified
2912 FunctionType::param_iterator I = Ty->param_begin();
2913 FunctionType::param_iterator E = Ty->param_end();
2914 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
2916 std::vector<Value*> Args;
2917 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2918 if ((*ArgI).V->getType() != *I)
2919 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
2920 (*I)->getDescription() + "'");
2921 Args.push_back((*ArgI).V);
2924 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2925 error("Invalid number of parameters detected");
2927 $$ = new InvokeInst(V, Normal, Except, Args);
2929 cast<InvokeInst>($$)->setCallingConv(upgradeCallingConv($2));
2934 $$ = new UnwindInst();
2937 $$ = new UnreachableInst();
2942 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2944 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
2947 error("May only switch on a constant pool value");
2949 BasicBlock* tmpBB = getBBVal($6);
2950 $$->push_back(std::make_pair(V, tmpBB));
2952 | IntType ConstValueRef ',' LABEL ValueRef {
2953 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2954 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
2957 error("May only switch on a constant pool value");
2959 BasicBlock* tmpBB = getBBVal($5);
2960 $$->push_back(std::make_pair(V, tmpBB));
2965 : OptAssign InstVal {
2968 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
2969 if (BCI->getSrcTy() == BCI->getDestTy() &&
2970 BCI->getOperand(0)->getName() == $1)
2971 // This is a useless bit cast causing a name redefinition. It is
2972 // a bit cast from a type to the same type of an operand with the
2973 // same name as the name we would give this instruction. Since this
2974 // instruction results in no code generation, it is safe to omit
2975 // the instruction. This situation can occur because of collapsed
2976 // type planes. For example:
2977 // %X = add int %Y, %Z
2978 // %X = cast int %Y to uint
2979 // After upgrade, this looks like:
2980 // %X = add i32 %Y, %Z
2981 // %X = bitcast i32 to i32
2982 // The bitcast is clearly useless so we omit it.
2988 setValueName($2.I, $1);
2994 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2995 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
2997 Value* tmpVal = getVal($1.T->get(), $3);
2998 BasicBlock* tmpBB = getBBVal($5);
2999 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
3002 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3004 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
3005 BasicBlock* tmpBB = getBBVal($6);
3006 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
3010 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
3011 $$ = new std::vector<ValueInfo>();
3014 | ValueRefList ',' ResolvedVal {
3019 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
3022 | /*empty*/ { $$ = 0; }
3035 : ArithmeticOps Types ValueRef ',' ValueRef {
3036 const Type* Ty = $2.T->get();
3037 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<PackedType>(Ty))
3038 error("Arithmetic operator requires integer, FP, or packed operands");
3039 if (isa<PackedType>(Ty) &&
3040 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
3041 error("Remainder not supported on packed types");
3042 // Upgrade the opcode from obsolete versions before we do anything with it.
3043 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3044 Value* val1 = getVal(Ty, $3);
3045 Value* val2 = getVal(Ty, $5);
3046 $$.I = BinaryOperator::create(Opcode, val1, val2);
3048 error("binary operator returned null");
3052 | LogicalOps Types ValueRef ',' ValueRef {
3053 const Type *Ty = $2.T->get();
3054 if (!Ty->isInteger()) {
3055 if (!isa<PackedType>(Ty) ||
3056 !cast<PackedType>(Ty)->getElementType()->isInteger())
3057 error("Logical operator requires integral operands");
3059 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3060 Value* tmpVal1 = getVal(Ty, $3);
3061 Value* tmpVal2 = getVal(Ty, $5);
3062 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
3064 error("binary operator returned null");
3068 | SetCondOps Types ValueRef ',' ValueRef {
3069 const Type* Ty = $2.T->get();
3070 if(isa<PackedType>(Ty))
3071 error("PackedTypes currently not supported in setcc instructions");
3072 unsigned short pred;
3073 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3074 Value* tmpVal1 = getVal(Ty, $3);
3075 Value* tmpVal2 = getVal(Ty, $5);
3076 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3078 error("binary operator returned null");
3082 | ICMP IPredicates Types ValueRef ',' ValueRef {
3083 const Type *Ty = $3.T->get();
3084 if (isa<PackedType>(Ty))
3085 error("PackedTypes currently not supported in icmp instructions");
3086 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3087 error("icmp requires integer or pointer typed operands");
3088 Value* tmpVal1 = getVal(Ty, $4);
3089 Value* tmpVal2 = getVal(Ty, $6);
3090 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3094 | FCMP FPredicates Types ValueRef ',' ValueRef {
3095 const Type *Ty = $3.T->get();
3096 if (isa<PackedType>(Ty))
3097 error("PackedTypes currently not supported in fcmp instructions");
3098 else if (!Ty->isFloatingPoint())
3099 error("fcmp instruction requires floating point operands");
3100 Value* tmpVal1 = getVal(Ty, $4);
3101 Value* tmpVal2 = getVal(Ty, $6);
3102 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3107 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3108 const Type *Ty = $2.V->getType();
3109 Value *Ones = ConstantInt::getAllOnesValue(Ty);
3111 error("Expected integral type for not instruction");
3112 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3114 error("Could not create a xor instruction");
3117 | ShiftOps ResolvedVal ',' ResolvedVal {
3118 if (!$4.V->getType()->isInteger() ||
3119 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3120 error("Shift amount must be int8");
3121 if (!$2.V->getType()->isInteger())
3122 error("Shift constant expression requires integer operand");
3123 $$.I = new ShiftInst(getOtherOp($1, $2.S), $2.V, $4.V);
3126 | CastOps ResolvedVal TO Types {
3127 const Type *DstTy = $4.T->get();
3128 if (!DstTy->isFirstClassType())
3129 error("cast instruction to a non-primitive type: '" +
3130 DstTy->getDescription() + "'");
3131 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3135 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3136 if (!$2.V->getType()->isInteger() ||
3137 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3138 error("select condition must be bool");
3139 if ($4.V->getType() != $6.V->getType())
3140 error("select value types should match");
3141 $$.I = new SelectInst($2.V, $4.V, $6.V);
3144 | VAARG ResolvedVal ',' Types {
3145 const Type *Ty = $4.T->get();
3147 $$.I = new VAArgInst($2.V, Ty);
3151 | VAARG_old ResolvedVal ',' Types {
3152 const Type* ArgTy = $2.V->getType();
3153 const Type* DstTy = $4.T->get();
3154 ObsoleteVarArgs = true;
3155 Function* NF = cast<Function>(CurModule.CurrentModule->
3156 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3159 //foo = alloca 1 of t
3163 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3164 CurBB->getInstList().push_back(foo);
3165 CallInst* bar = new CallInst(NF, $2.V);
3166 CurBB->getInstList().push_back(bar);
3167 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3168 $$.I = new VAArgInst(foo, DstTy);
3172 | VANEXT_old ResolvedVal ',' Types {
3173 const Type* ArgTy = $2.V->getType();
3174 const Type* DstTy = $4.T->get();
3175 ObsoleteVarArgs = true;
3176 Function* NF = cast<Function>(CurModule.CurrentModule->
3177 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3179 //b = vanext a, t ->
3180 //foo = alloca 1 of t
3183 //tmp = vaarg foo, t
3185 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3186 CurBB->getInstList().push_back(foo);
3187 CallInst* bar = new CallInst(NF, $2.V);
3188 CurBB->getInstList().push_back(bar);
3189 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3190 Instruction* tmp = new VAArgInst(foo, DstTy);
3191 CurBB->getInstList().push_back(tmp);
3192 $$.I = new LoadInst(foo);
3196 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3197 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3198 error("Invalid extractelement operands");
3199 $$.I = new ExtractElementInst($2.V, $4.V);
3202 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3203 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3204 error("Invalid insertelement operands");
3205 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3208 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3209 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3210 error("Invalid shufflevector operands");
3211 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3215 const Type *Ty = $2.P->front().first->getType();
3216 if (!Ty->isFirstClassType())
3217 error("PHI node operands must be of first class type");
3218 PHINode *PHI = new PHINode(Ty);
3219 PHI->reserveOperandSpace($2.P->size());
3220 while ($2.P->begin() != $2.P->end()) {
3221 if ($2.P->front().first->getType() != Ty)
3222 error("All elements of a PHI node must be of the same type");
3223 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3228 delete $2.P; // Free the list...
3230 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
3232 // Handle the short call syntax
3233 const PointerType *PFTy;
3234 const FunctionType *FTy;
3235 if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
3236 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3237 // Pull out the types of all of the arguments...
3238 std::vector<const Type*> ParamTypes;
3240 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3242 ParamTypes.push_back((*I).V->getType());
3245 FunctionType::ParamAttrsList ParamAttrs;
3246 if ($2 == OldCallingConv::CSRet) {
3247 ParamAttrs.push_back(FunctionType::NoAttributeSet);
3248 ParamAttrs.push_back(FunctionType::StructRetAttribute);
3250 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3251 if (isVarArg) ParamTypes.pop_back();
3253 const Type *RetTy = $3.T->get();
3254 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3255 error("Functions cannot return aggregate types");
3257 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg, ParamAttrs);
3258 PFTy = PointerType::get(FTy);
3261 // First upgrade any intrinsic calls.
3262 std::vector<Value*> Args;
3264 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3265 Args.push_back((*$6)[i].V);
3266 Instruction *Inst = upgradeIntrinsicCall(FTy, $4, Args);
3268 // If we got an upgraded intrinsic
3273 // Get the function we're calling
3274 Value *V = getVal(PFTy, $4);
3276 // Check the argument values match
3277 if (!$6) { // Has no arguments?
3278 // Make sure no arguments is a good thing!
3279 if (FTy->getNumParams() != 0)
3280 error("No arguments passed to a function that expects arguments");
3281 } else { // Has arguments?
3282 // Loop through FunctionType's arguments and ensure they are specified
3285 FunctionType::param_iterator I = FTy->param_begin();
3286 FunctionType::param_iterator E = FTy->param_end();
3287 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3289 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3290 if ((*ArgI).V->getType() != *I)
3291 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3292 (*I)->getDescription() + "'");
3294 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3295 error("Invalid number of parameters detected");
3298 // Create the call instruction
3299 CallInst *CI = new CallInst(V, Args);
3300 CI->setTailCall($1);
3301 CI->setCallingConv(upgradeCallingConv($2));
3314 // IndexList - List of indices for GEP based instructions...
3316 : ',' ValueRefList { $$ = $2; }
3317 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3321 : VOLATILE { $$ = true; }
3322 | /* empty */ { $$ = false; }
3326 : MALLOC Types OptCAlign {
3327 const Type *Ty = $2.T->get();
3329 $$.I = new MallocInst(Ty, 0, $3);
3332 | MALLOC Types ',' UINT ValueRef OptCAlign {
3333 const Type *Ty = $2.T->get();
3335 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3338 | ALLOCA Types OptCAlign {
3339 const Type *Ty = $2.T->get();
3341 $$.I = new AllocaInst(Ty, 0, $3);
3344 | ALLOCA Types ',' UINT ValueRef OptCAlign {
3345 const Type *Ty = $2.T->get();
3347 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3350 | FREE ResolvedVal {
3351 const Type *PTy = $2.V->getType();
3352 if (!isa<PointerType>(PTy))
3353 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3354 $$.I = new FreeInst($2.V);
3357 | OptVolatile LOAD Types ValueRef {
3358 const Type* Ty = $3.T->get();
3360 if (!isa<PointerType>(Ty))
3361 error("Can't load from nonpointer type: " + Ty->getDescription());
3362 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3363 error("Can't load from pointer of non-first-class type: " +
3364 Ty->getDescription());
3365 Value* tmpVal = getVal(Ty, $4);
3366 $$.I = new LoadInst(tmpVal, "", $1);
3369 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3370 const PointerType *PTy = dyn_cast<PointerType>($5.T->get());
3372 error("Can't store to a nonpointer type: " +
3373 $5.T->get()->getDescription());
3374 const Type *ElTy = PTy->getElementType();
3375 if (ElTy != $3.V->getType())
3376 error("Can't store '" + $3.V->getType()->getDescription() +
3377 "' into space of type '" + ElTy->getDescription() + "'");
3378 Value* tmpVal = getVal(PTy, $6);
3379 $$.I = new StoreInst($3.V, tmpVal, $1);
3383 | GETELEMENTPTR Types ValueRef IndexList {
3384 const Type* Ty = $2.T->get();
3385 if (!isa<PointerType>(Ty))
3386 error("getelementptr insn requires pointer operand");
3388 std::vector<Value*> VIndices;
3389 upgradeGEPIndices(Ty, $4, VIndices);
3391 Value* tmpVal = getVal(Ty, $3);
3392 $$.I = new GetElementPtrInst(tmpVal, VIndices);
3401 int yyerror(const char *ErrorMsg) {
3403 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3404 + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3405 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3406 if (yychar != YYEMPTY && yychar != 0)
3407 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3409 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3410 std::cout << "llvm-upgrade: parse failed.\n";
3414 void warning(const std::string& ErrorMsg) {
3416 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3417 + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3418 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3419 if (yychar != YYEMPTY && yychar != 0)
3420 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3422 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3425 void error(const std::string& ErrorMsg, int LineNo) {
3426 if (LineNo == -1) LineNo = Upgradelineno;
3427 Upgradelineno = LineNo;
3428 yyerror(ErrorMsg.c_str());