Quantcast
Channel: Visual C++ Team Blog
Viewing all 437 articles
Browse latest View live

Auto-Vectorizer – New Posts

$
0
0

If you are interested in the Auto-Vectorizer feature, shipping in Visual Studio 11, please hop over to the Native Concurrency blog, where we are now on episode 4.  The Overview post now includes a Table Of Contents, with links to each separate post.

Jim


The Metro style apps with C++ event is now a live webcast

$
0
0

As I mentioned a couple of weeks ago, we announced the Metro style apps with C++ event. Since we announced the camp, there were a lot of requests for a live webcast. Thanks to Jaime who just posted on this blog, the event will be broadcasted live!

Quoting Jaime:

Event sold out within a few days, and we got a lot of requests for it to be recorded (or broadcasted live)..  

I am happy to announce that the event will now be live.  Please pencil us in in your calendar. Event will be live on Friday May 18th, from 9 AM PST to 5 PM PST.

We will share details (the link) and the agenda later this week.   We will aim to have two live Q&As (one around noon PST) and one around 4 PM PST, we will take your questions via twitter.. Just follow the #win8C++Camp on the day of the event..

Thanks,

Vikas Bhatia.

VC++ PM

Follow the Windows 8 Metro style event live

Unit test framework in VS11

$
0
0

We provide the ability in Visual Studio 11 to do native unit testing, with a new C++ unit testing framework shipping in the box. We’re really happy to enable this support for our C++ developers, so you no longer need to use the “/clr” flag or fall back to 3rd party frameworks. Read here for more details.

C++ Build Throughput: Visual Studio 11 Pre-Release Compared to Visual Studio 2010 SP1

$
0
0

Hi my name is Li Shao. I am a Senior Software Design Engineer in Test in the Visual C++ group. In this blog, our team would like to review Visual Studio 11 (VS11) Desktop application build throughput compared to Visual Studio 2010 SP1 (VS10). Jim Hogg, Mark Hall, Bill Bailey, Mohamed Magdy Mohamed, and Valentin Isac have also contributed to this blog. You can refer to the Blog by Tim Wagner if you are interested in the new Metro Style application build throughput.

Build throughput is one of the most important productivity factors for C++ developers, and so build throughput testing is a vital component of our overall performance testing for Visual C++. We have targeted build throughput tests for the compiler and linker, and we also have build throughput tests for the MSBuild build engine. For every release, we have performance tests to check the overall end to end build performance, including time spent in the compiler front-end, back-end, and linker. For those of you who may not know, the compiler front-end is the phase that parses and analyzes the source code to build the intermediate representation (IR) of the program. The compiler back-end is the phase that takes the IR as input, and performs optimizations and generates code in the form of object files. The linker takes these object files as input and assembles them into an executable file. In the case of building with /GL (compile for link-time code generation, or LTCG), code generation and optimization happen during the linker phase where the IR for the entire executable can be analyzed.

Every new release of Visual C++ contains a large amount of new technology and features available to customers in the form of source code libraries and header files. For a given compiler, the more source code you have, the longer it takes to compile. Fortunately, processor advances over the years have offset this increase in functionality. In recent releases, as processor speeds began topping out, we have invested in multi-core features, such as Multi-Proc MSBuild, and the /MP compiler switch. In VS11, we multi-threaded the backend. For builds that require a lot of optimization time, this has netted some great wins. For example, Microsoft’s SQL build is 30% faster thanks to reduced back-end times.

The increase in functionality in VS11 is among the largest delta we’ve ever shipped. As we integrated all this new technology into the product, our performance tests told us how it was affecting overall build performance versus previous releases. Even though the amount of new source code being compiled rose significantly, in most cases, build time increases were held to an acceptable delta.

However, based on our testing results, if you have an application which uses the Standard Template Library heavily, you may notice slower builds due to the increased functionality mandated by the C++ Standard. In this blog, we will analyze the build throughput of a representative application to demonstrate the improvements we made and possible slowdown you may experience.

 

Build Throughput Data from “real world” Applications

Our end to end throughput tests use production-level, “real world” applications. We refer to them as RWC (Real World Code). Here is the build throughput data from an internal, post-Beta version of VS11 on one of our RWC projects across different machine configurations. This particular desktop application has about 50 C++ projects, with 2.8 million lines of code (LOC). The application makes heavy use of the Standard Template Library. The “RWC” below refers specifically to this application.

 

Configuration ProcessorType ProcessorNumber RAM OS (Windows 7 SP1)
Name  (GB)
Spec A  Intel Core I7 4 core (8 threads) 16  x64
(E31240)
Spec B Intel Core 2 Quad 4 core (4 threads) 8  x64
(Q9550)
Spec C Intel Pentium 2 Core (2 threads) 3  x86
(G6950)

 

clip_image002

Figure 1: RWC Build Throughput (MSBuild 2 Proc (/m:2) and Full Optimization (/Ox))

 

clip_image004

Figure 2: RWC Build throughput with link /LTCG (LTCG: Link Time Code Generation, MSBuild 2 Proc (/m:2), Compile with /GL, link with /LTCG)

 

clip_image006

Figure 3: RWC Compiler Back-end throughput (MSBuild 2 Proc (/m:2))

 

clip_image008

Figure 4: RWC Link time throughput (MSBuild 2 Proc (/m:2))

 

“Full Build time” is measured from when the build starts until the build finishes. It is the clock time that it takes for the build to finish. Compiler front-end (FE), compiler back-end (BE), and link time are the total time (accumulated time) spent in the C1.dll & C1xx.dll (FE), C2.dll (BE) and linker across all processes. Since this is a multi-proc build, and some of the projects have /MP enabled for compiler, generally there is more than one instance of the compiler running, which is why the total time spent in the tools is much larger than the “Full Build Time”.

In the non-LTCG build (Figure 1), the linker does minimal work compared with the rest of the components, therefore the linker time is hardly visible from the graph. Likewise, in LTCG build (Figure 2), all the code generation happens after linking. Since the linker eliminates all redundant template instantiations across the object files before the back-end runs, the back-end time is drastically reduced in this scenario.

Based on our data when running multi-proc MSBuild (MSBuild /M:n) on this particular application, building with 4-8 Proc can give slight throughput improvement over 2 Proc for overall build time. However, due to resource contention and project reference limitation on paralleled builds that can actually happen, a 2-Proc build is representative of multi-proc build characteristics for this application in terms of overall throughput. Therefore, we are using the 2 Proc data here to present the build throughput.

Here are some key observations based on the data:

 

Faster Compiler Back-end phase

In VS11, we have introduced a new feature to support creating multiple compiler back-end threads to improve build performance. The compiler back-end performs optimization and code generation on a single function at a time, allowing it to generate code for multiple functions in parallel. This can be a win, especially for code generation with optimizations enabled, as performing optimizations requires the back-end to spend more time in each function.

This throughput win can be seen in Figure 1 and Figure 3. While these are impressive improvements in compiler back-end throughput, we note that in this scenario the back end time is a small fraction of the total build time. We highlight it here for illustration purposes only.

 

Slower Compiler Front-end phase

We can see that there is 15% - 20% performance degradation in the VS11 front-end compared to VS10 in this real world example (Figure 1 and Figure 2). Our investigation revealed that this performance degradation is not in the compiler itself but rather is a function of the increased number of template instantiations being processed by the front-end. New functionality added to the STL, significantly increases the number of template instantiations in a given compilation. This major increase of the functionality is mandated by the new C++ Standard and is also widely requested by our customers. The increase in template types forces the front end to instantiate many more templates for a given input file, which causes the overall build performance to degrade. Of course, we haven’t shipped VS11 yet, so we continue to analyze this issue and look for ways to improve throughput.

As we mentioned earlier, the linker takes the intermediate files generated by the compiler and produces the final assembly. As a result of larger intermediate files generated by the compiler, you may also see slight slowdown in link time for both un-optimized build and optimized build (LTCG), especially on lower end machines (Spec C as we presented) due to more symbols to process and merge.

 

Faster LTCG Build

On a high end machine (Spec A and Spec B as we presented), our tests show faster link time in LTCG builds (Figure 4).

For a number of releases the compiler has supported Link Time Code Generation (LTCG), whereby code generation is deferred to link-time so that information on all modules for the entire image (EXE, DLL) is made available for optimization. Thus, code generation can be done in the context of the entire image, inlining across modules, application of custom calling convention, etc. Non-LTCG builds generally limit optimizations to within the context of a single object file.

With VS11, this link-time code generation can be done in multiple threads, compiling more than one function at a time, caveat dependencies as determined by the function call tree. This is a particularly good win for projects that compile into fewer, larger images. Our data shows that when building a “big EXE” Microsoft product, SQL Server, build time improved ~30% due to the work we did to improve LTCG build throughput. Note that SQL Server sources do not use template code, which is why it does not have the build throughput degradation caused by the new STL templates.

 

How to improve your application’s build performance?

Since build throughput is very important to C++ developer productivity, here are a few suggestions that can help you improve build throughput.

Take advantage of the CPU cores on your machine

From Figure 1 and Figure 2, you can see that although the total FE time has regressed, the regression in the overall build time is still very minimal on the particular application, especially on high-end machines (Spec A and Spec B). This is due to the effect of MultiProc build. When building in the IDE, the Build system will use the total number of cores on your machine by default. You can also modify multi-proc build by going to Tools -> Options -> Projects and Solutions -> Build and Run, changing the setting for “Maximum number of Parallel Project Builds”. If you are building on the command line, pass in /m:n (n is the numbers of processes you would like to use). The default when building with MSBuild on the command line is 1. As mentioned earlier, although building with 4 or more procs might give you better performance, for this particular application, setting MSBuild to 2 proc build (/m:2) gives the performance that is close to 4 or 8 proc build. In addition, you can also set /MP per project or per file to take advantage of compiler level multi-process build. For additional suggestions on how to further tune your build, you can take a look of this blog.

Use Pre-Compiled Headers (PCH)

C++ library headers represent a collection of living, evolving libraries, and they tend to increase in size from release to release. In VS11, for example, the windows headers increased in raw size by 13%. This is due to adding more API functions and types related to Windows 8. The new Windows headers will add more compile time when the PCH is created, not when it is used. Once built, there are many more compiles that use the PCH, whose build time are affected only a tiny amount, if at all. Proper use of precompiled headers continues to be the most effective way to reduce overall build times. If your application uses template extensively, you may also consider pre-instantiate the template types in PCH files.

A small experiment shows the difference using PCH achieves for a single project with around 200 files. Each file has around a hundred lines of code. Various library headers are included in the PCH.

clip_image010

Figure 5: PCH impact of minimizing the effect of size increase of library headers

 

Use Managed Incremental Build

If you have a managed application, you may take advantage of the managed incremental build to avoid doing a full build when the referenced assemblies have insignificant change. For more information, you can read this blog.

 

Summary

We have made significant throughput improvements to the Compiler Back-end and Linker build phases. If you have an application that is not a heavy user of STL and spend a lot of time in optimization, you should see the build time improvement.

The increase of template types will play a dominant role in the overall build throughput for applications with extensive templates. Applications that use the STL extensively may experience longer build times due to changes mandated by the C++11 Standard. You may also experience slightly longer build time due to the increased number of total headers files in VS11 and Windows 8.

To improve the overall build time, you can take advantage of the multiple cores on your machines to do multiproc builds. Also make sure to use Pre-Compiled headers (PCH). For managed C++ application, be sure to have managed incremental build turned on to improve incremental build performance.

 

Let Us Know!

We are interested in getting your build throughput performance data if you see any improvement, or slowdown beyond what you might expect from some amount of growth in header files or usage of STL templates when migrating your applications to VS11. You may reply to the blog or send email to lishao at Microsoft dot com.

In addition to capturing the overall build time, you can get compiler and linker time for each compiler/linker instance by passing /Bt to Compiler and /Time to Linker.

· When building in the IDE, you can set /Bt as the additional options for compiler and /Time as the additional options for linker. Make sure you build the application with “Detailed” verbosity. To set the verbosity, you can go to Tools -> Options -> Project and Solutions -> Build and Run, set “MSBuild Project Build Verbosity” to “Detailed”.

· For command line build, you can set _CL_=/Bt and _LINK_=/Time in the build environment and build with MSBuild /v:d option.

In your build log, you will see the time spent in C1.dll (FE), C1xx.dll (FE), C2.dll (BE) and linker for each instance of the compiler and linker. You may need to write a simple script to add up those numbers. Please let us know if you would like us to post a script that can do the work. Alternatively, you can enable MSBuild “Diagnostic” logging. It will give you the time spent in Compiler task and linker task, which is close to the compiler and linker time.

We hope that this blog can help you understand more about C++ desktop application build throughput in VS11. If you are interested in C++ Metro Style Application build throughput, which are new for VS11, you can take a look at this blog to get an overview. Note that, we continue to make improvement in C++ Metro Style application build throughput. You should see about 20% overall build throughput improvement compared to Beta in the upcoming release.

Please let us know if you have any feedback. We appreciate your input to help us improve build performance.

Be What’s Next (We’re hiring!)

$
0
0

The C++ organization is growing and hiring across all feature areas (C++ 11, compiler front-end, compiler back-end, C++ AMP, PPL, libraries & runtime, IDE, Casablanca). We are looking for passionate program managers, developers and testers to bang out the next versions of the toolset!

 

What’s in it for you:

  1.          Be part of the C++ standards evolution - you’ll have the opportunity to work side-by-side with folks like Herb Sutter ![if>
  2.          Solve exciting challenges as we navigate the hardware evolution (newer chipsets, multi-core, GPU, heterogeneous cores etc.) ![if>
  3.          Be part of the technology that builds all of Microsoft’s platforms like Windows, Xbox, Windows Phone and Windows Embedded.![if>

 

Please apply directly using the links below. We’ll keep this list updated for the next couple of months.

Program Management

Software Development

Testing

 

C++ in Visual Studio 2012 Express for Windows Desktop

$
0
0

In case some of you missed it, Soma recently announced Visual Studio Express 2012 for Windows Desktop development. This express edition will include the latest VC++ compiler and libraries, which is great for students, new developers and open source application developers.

Please follow the link to see more details and to contribute to the discussion.

What bugs were fixed in MFC in Visual Studio 2012?

$
0
0

Pat Brenner

Hello, I’m Pat Brenner, a developer on the Visual C++ Libraries team. I recently shared some information about the Microsoft Foundation Class (MFC) Library in this blog post. Several people responded to that post asking for a list of bugs that have been fixed in MFC for Visual Studio 2012.

Though I cannot provide a complete list of the bugs in our internal bug database, here is a list of the bugs that were reported by customers through our Connect site that have been fixed in MFC for Visual Studio 2012 RTM. Click on any Connect bug number to see more information about that bug.

 

Connect # Bug Title
574974 CRecordset/DoFieldExchange not working properly
577870 CMFCButton causes memory leak
582449 Multiple floating CDockablePanes have issues when docked together
584677 MFC projects targeted for Windows XP cause stack corruption.
584688 Allow type safe alternatives for the min() and max() macros to be used
585121 Windows 7 taskbar won't auto-unhide when wizard-built MFC app is maximized
585837 It is possible to dock a CDockablePane to one that has already been closed
588167 Suggestion for CMFCToolBarsCustomizeDialog
588348 CWinApp causes access violation by using uninitialized data
594556 Incorrect background for controls on a CPaneDialog
595648 CMFCToolBar::m_bDontScaleImages variable is available only for static link
599305 Unable to link against CMDIChildWndEx::m_dwDefaultTaskbarTabPropertyFlags
600357 Incomplete documentation for CMFCColorButton class
611434 Access violation in afxcustomizemenubutton.cpp
613377 Memory Leaks in MFC Class
613594 AFX_TAB_TEXT_MARGIN not exported when linking dynamically with MFC
615996 Symbol afxGlobalUtils - C++
618207 CDockablePane undocking issue with swapped mouse buttons
618539 Window menu in MFC app does not work correctly
619673 CMFCDropDownListBox::OnDrawItem should use DT_NOPREFIX
619913 Static MFC executables twice as large
620733 MFC Feature Pack Customisation Dialogue Box: "All Commands"
621222 <<OLE VERBS GO HERE>> does not disappear from the menu
622001 Inclusion of MFC headers causes leaking memory
622495 Floating pane's docking status is not restored correctly after LoadState
622942 #include <afxcontrolbars.h> is not compatible with #define NOMINMAX
623229 CMFCShellListCtrl controls do not show properly translated headers
624043 MFC bug? in-process QAxServer leaves dangling COleFrameHook reference
626013 MFC application with a ribbon: An underline is displayed on the title
626016 MFC application with a ribbon: When closing the maximized child MDI window
629703 MFC: Disabling DWM Composition causes redraw issues
630000 CDockablePane derived class after LoadState is not restored correctly
630199 Buffer overrun in CRichEditCtrl::GetTextRange with MBCS
631089 Sample CLIPART Common.res missing
631723 BUG in MFC Undermines Application Developer Control over the application
632178 DTS:  CWnd::PreCreateWindow change causing problems
632542 MFC Ribbon tooltips are below floating panes
632550 Copy/Paste is not working in dockable pane
632888 D2D1::ColorF::Red gives blue and D2D1::ColorF::Blue gives red
634898 Issue with CMFCToolBarImages::AddImage with 32bit Images
635527 CWnd::CreateIndirect memory leak in VS2005, VS2010, VS2010 SP1
635819 New file "afxanimationcontroller.h" uses TRACE instead of ATLTRACE
636148 AfxOleUnregisterTypeLib cannot handle win64 typelibs
636860 MFC Suitable for COM development ? (dllmain violations)
638564 Using the mouse wheel to scroll in CMFCPopupMenu does not work correctly
641001 CCheckListBox incorrectly displays BST_INDETERMINATE check state
641098 MFC feature pack: incorrect tool bar drawing for fixed tool bars (non-dockable)
641100 MFC timer IDs used to handle docking capabilites are in very normal usage range
641292 CMFCStatusBar incorrectly assumes WS_THICKFRAME and SBARS_SIZEGRIP
641665 EnableLoadWindowPlacement(false) does not work correctly
641672 Could CMFCStatusBar RecalcLayout() become virtual?
642053 CMFCMenuBar and Accessibility
643639 The state of warning 4100 is not restored to the previous state
643999 CMFCToolBarImages may cause ActiveX host shutdown failure
644774 MFC taskbar interaction with maximize/minimize has issues
646445 CVSListBox produces memory Leaks
646481 Symbol afxKeyboardManager not exported when linking dynamically
650162 MFC MDI standard tabs close unexpectedly when activated by click in [x] location
651057 MFC headers in VS 2010 SP1 causes /doc compilation to fail
653308 MFC Ribbon Bug - incorrectly calculated panel widths
656884 Windows 7 style ribbon bar context categories look bad
658227 MFC status bar message is displayed (wrong) again after tool bar button is pressed
658568 CMFCDesktopAlertWnd::Create() method doesn't show a window
661289 COleObjectFactory Registry Registration fails with blanks in Path
670846 Error in CWinAppEx::GetSectionString
672452 MFC - CDialogEx - Deactivating and activating dialog set focus to first dialog item
675922 CMFCPopupMenu context menu not shown in foreground in TrayMenu sample
676869 MFC Tabbed MDI bug
679332 Crash in AdjustLayout using CMFCPropertyGridCtrl
679390 Missing DLL exports in MFC
680263 CMFCRibbonEdit::OnSetFocus() in MFC Microsoft Office Fluent UI
681491 Toolbar using CMFCToolBarComboBoxButton not displayed correctly
681771 CMFCPropertySheet - RemovePage not working with PropSheetLook_OutlookBar
683164 MFC Ribbon's Gallery Button's Column property does not work
683598 Compile error in Visual Studio 2010 SP1 when using the "lint" preprocessor definition
683726 Using CFileDialog in Loop causes Error
684318 CMFCToolBarsMenuPropertyPage SYSTEM_DEFAULT_ANIMATON fails to initialize
684376 Deriving from CMFCHeaderCtrl requires CMFCListCtrl changes
685022 CWnd::OnWndMsg has incorrect cast for AfxSig_v_u_v
686157 Satellite DLLs doesn't work when new MFC controls like CMFCButton are used
687615 VS2005 migrated app has toolbar bugs, including Win7 Aero drawing bug
687736 MFC class CStreamOnCString stops working with IE9
688159 CLinkCtrl::GetItemState never returns the item state
692769 MFC - CRecordset::GetFieldValue throws "Invalid Argument Value" exception
694793 MFC - CRecordset::GetFieldValue and nvarchar(MAX) returns no data
696791 MFC CPropertySheet crashes when WM_CREATE returns -1
698304 CMFCPropertyGridCtrl vertical scrollbar doesn't work correctly in alphabetic mode
699739 CString::FormatMessage can throw out of memory exception
700173 Display bug in CMFCRibbonComboBox control
705542 CMFCButton proceeds mouse events in region covered by another MDI child window
709116 CMFCFontComboBox memory leak after DeleteString
711714 MFC unsafely uses GetModuleHandle behind the scenes, causing crash
715991 Any default SDI application type with MFC standard project style always crashes
717004 Problem with Print Preview in a tabbed MDI application with splitter window
717992 CMFCOutlookBarTabCtrl memory leak
718189 GDI leak when closing last document tab in an MDI application
720671 Black area in tab control of CTabView and live taskbar preview window
720894 GDI object leakage in CMFCToolBarImages::SmoothResize function
722441 Ribbon Menus unexpectly show the panel icon
724022 DECLARE_DYNAMIC in CMFCEditBrowseCtrl missing
725299 Hung process upon exiting MFC application when using Speech Recognition
725331 Draw Bug in CView Frame on Initial Focus
726453 MSDN Forum: GDI - Issue while drawing Arc
731161 MFC Ribbon buttons no longer working with touchscreen monitor
731201 Incorrect XML in MFC header files causes compiler warnings
731341 Titlebar goes 'black' and unresponsive after (some) screensavers have run
736941 Memory leak from SetPaneSize sample in MFC 2008 feature pack
738284 Ok/Cancel/Apply buttons missing from MFC Property sheet on Hebrew Windows 7
738924 CFileDialog FileNamedlg
740600 CMFCColorButton will be displayed without style/theme
745790 Static MFC executables produced by Visual Studio 2012 RC are huge
746564 VS 2012 RC - Code Analysis: CUIAnimationCallbackBase --> C6388

 

I hope you find this information useful. As you can see, we do pay attention to and take action on the bugs that are reported on the Connect site. So please continue to report bugs that you find in MFC (or any of the Visual C++ libraries)—we do want to hear about them.

Pat Brenner
Visual C++ Libraries Development Team


Targeting Windows XP with C++ in Visual Studio 2012

$
0
0

We recently announced the Visual Studio 2012 product lineup and platform support, and as a part of this announcement we mentioned that we were evaluating options for enabling C++ developers to build applications in Visual Studio 2012 that run on Windows XP without requiring side-by-side installation of Visual Studio 2010. Today I would like to share more details about this capability.

Background
The C++ runtime and libraries that accompany Visual Studio 2012 contain dependencies on several Windows API functions that exist only on Windows Vista and higher versions of the OS.  This means that applications built with Visual Studio 2012’s C++ compiler will fail to load and execute on Windows XP. Developers wishing to target Windows XP can use Visual Studio’s C++ multi-targeting feature, which enables the use of the Visual Studio 2010 compiler from within the new IDE. Multi-targeting enables developers to take advantage of the new features of the IDE without migrating projects to the new compiler or to use the Visual Studio 2010 compiler to build applications that target Windows XP.

Assessing Multi-targeting
The Beta release of Visual Studio 2012 offered us an opportunity to evaluate the effectiveness of C++ multi-targeting, particularly among developers that wish to target Windows XP. Feedback from customers cited two key scenarios they wanted Visual Studio 2012 to support in order to best meet their needs for Windows XP targeting:

  1. The ability to target Windows XP and higher from a single compiler and tools chain rather than resort to separate builds for XP and for Vista+.
  2. The ability to target Windows XP and higher from a single code base that employs modern C++11 language features.

In order to better meet customer needs relative to build configuration and XP targeting, we have made the decision to enhance multi-targeting to support Windows XP targeting directly from the Visual Studio 2012 C++ compiler and libraries.

Enhancing Multi-targeting
Later this fall, Microsoft will provide an update to Visual Studio 2012 that will enable C++ applications to target Windows XP. This update will make the necessary modifications to the Visual C++ 2012 compiler, runtime, and libraries to enable developers to create applications and DLLs that run on Windows XP and higher versions as well as Windows Server 2003 and higher. This update will also be included in the recently-announced Visual Studio Express 2012 for Windows Desktop.

Steve Teixeira
Director of Program Management
Visual C++

STL Bugs Fixed In Visual Studio 2012

$
0
0

After Pat's post last week about MFC bugs fixed in Visual Studio 2012 (aka VC11), I thought that a similar list for the STL would be interesting:

ID Title
492128 std::locale constructor modifies global locale via "setlocale()"
492561 STL streams cannot be used concurrently
498533 iostreams should use codepage of their imbued locales instead of the current c locale
506966 New warning 4986 prevents clean compile at warning level 4
524342 Implement std::max_align_t in Visual C++
532883 Visual C++: int_fast8_t Not Always Signed
532897 Problems constructing a bitset from an unsigned long in the VC RC
533131 Bug in std::deque. Non-conforming invalidation of iterators after pop_front()
533464 The <initializer_list> header in the VC10 release candidate
534457 C++ map<tuple<...>, V> compilation problems
534756 std::is_function does not work on rvalue reference types
539946 search_n fails with a Debug Assertion
540098 Problem with non-const operator() and bind
540813 Add support for the new C++0x library
541226 C++ Defect Report 445 Implementation
548693 Visual C++: numeric_limits<char> min/max incorrect when using /J
552541 Library or compiler bug with Visual C++ 2010
553629 Visual C++ forces conversion to char in push_back
556348 C++ compiler NULL broken??
557117 std::unordered_set equality comparison broken in Visual C++ 2010
558044 std::copy should not check _Dest when _First == _Last
558339 tr1:regex has different behavior between vs2008 and vs2010 on some regular expression
558993 std::pair members are not members of std::pair
560987 In Visual C++ 2010, std::tr1::shuffle_order_engine incorrectly defines min and max members, rendering the class (and std::tr1::knuth_b) unusable
560994 In Visual C++ 2010, std::tr1::discrete_distribution and std::tr1::negative_binomial_distribution are missing nested input_type types, making them unusable with std::tr1::variate_generator
565500 Crash in C++ runtime when compiling with /MDd and /vd2 switch
565748 Include support compile-time rational arithmetic specified in C++0x
566516 std::ifstream/std::ofstream change double value
567859 Visual C++: std::unordered_map Destructor Performance in Debug Configuration
568054 std::use_facet interferes with subsequent call to FatalExit
569997 [VC10] Compiler refers to std::shared_ptr as std::tr1::shared_ptr
571397 C++ setfill Can't Be Applied To wofstream - Irritating Error Message
576750 [C++0X] std::to_string is non conforming
577672 iterator assignment operator crashes in debug builds due to stl changes in vc10
596771 type_info::before returns type of int and not bool
598887 const const_iterator cannot be supplied to set::insert
603381 VS2010 STL for_each implementation breaks existing code
606746 Incorrect Overload Resolution
612692 std::bitset
616702 operator>> for basic_istream crashes with multibyte character set as locale
616827 Nested std::bind functions give bad error (with no reference to the file being compiled)
618807 Calling a bound lambda through a std::function variable
621653 Including stdint after intsafe generates warnings
626291 STL hash element cannot hash custom allocated strings
627639 std::fstream use 32-bit int as pos_type even on x64 platform
628197 std::string::erase is stupidly slow when erasing to the end, which impacts std::string::resize
633809 std::thread
633905 Visual C++: Ill-Formed unique_ptr Function Call Syntax
635833 std::uniform_int_distribution and std::uniform_int not returning correct values
635837 Low value of std::uniform_int_distribution and std::uniform_int not appearing when it's set to a negative number
640602 VS2010 Debugger: watching std::string with _ITERATOR_DEBUG_LEVEL = 0 does not work
640619 Move-construction can slice objects
640961 Visual C++: Argument Forwarding Bugs in std::bind Function Callers
641845 std::regex bug in vs2010
642277 std::regex bug in vs2010
642557 [random] uniform_int_distribution can produce out of range results
642600 system_error::what() returns incorrect value
645116 VC10 STL: emplace functions are not implemented for more than 1 parameter
645641 tr1 regex crashes in debug builds due to illegal use of iterator
646532 strsafe.h triggers many warnings with STL header files
648543 tr1::regex doesn't match a valid pattern with repetition
649268 std::bind and std::function generate a crazy number of copy.
649274 std::bind and std::function are not move-aware
649531 Compile error when explicitly instantiating shared_ptr
650567 Unhomed std::locale::facet and std::locale::_Locimp destructors cause crashes
651285 std::ref works incorrectly with classes that overload operator &
668921 std::numeric_limits<float>::max_digits10 value of 8 is wrong and should be 9
671328 Visual C++: User-Defined Bind Expressions with std::bind
674424 tr1 regex case-insensitive search not working
674652 non-conformant behavior of std::minmax in MSVC 2010
680313 std::merge invalidates source data because it uses move semantics
683483 MFC C++ fails to compile use of codecvt_utf8 in Debug Configuration
685726 INT64_C and UINT64_C should be defined in more cross-platform way
688731 std::bind with std::reference_wrapper<T> argument doesn't work on function object with template operator()
688797 std::thread crashes with error "f:\dd\vctools\crt_bld\self_x86\crt\src\thr\mutex.cpp(206): unlock of unowned mutex"
689342 unordered_map thousand time slower than the vc++ 2010 version
689689 Visual C++ (VS2010): Incorrect returned value of uniform_int_distribution
692248 Visual C++ ostringstream & ios_base::app broken
692988 std::vector::resize should take a const reference
694663 Check inside std::vector::_Reserve() triggers integer underflow and fails to detect invalid parameter passed to std::vector::resize()
694704 std::vector::reserve() contains a suboptimal check against max_size
694705 std::vector::_Insert() contains a suboptimal check against max_size
694881 std::vector::_Reserve() contains a suboptimal check against max_size
694887 std::vector::_Insert_n() contains a suboptimal check against max_size
695529 std::exception_ptr does not satisfy the requirements of NullablePointer
696109 std::pair move constructor not standard conformant, potentially dangerous behavior for pair of references
696151 std::reference_wrapper does not work with lambda functions
696316 Typo in std::deque::resize() comment
698286 std::begin and std::end ADL lookup failure
705089 C++ std::atomic<> missing constructor
705152 This instantiation of std::codecvt template does not meet standard requirements for std::codecvt::out
705993 Incorrect Type Name references in defaultvis.natvis visualizers for standard library
707067 Failed to parse expression: class "std::_Ref_count_base" has no member "Uses"
712897 Invalid ## arguments in _VAR_TYPE in xstddef
712984 std::uniform_int_distribution produces incorrect results when min0 is negative
714853 valarray operator[] const
716468 Heap corruption when CObject-derived class throws from constructor when being called from make_shared
716995 std::make_shared needs default constructor to compile
718865 STL: hypot not hoisted into the std namespace by cmath
721456 Debugger cannot display content of the std::string - "<Error reading characters of string.>"
721786 stdint.h UINTPTR_MAX has the same value as UINT32_MAX for 64-bit platforms
723427 Compile error in mutex
726398 Creating threads using std::thread class causes application crash
727368 std::reference_wrapper fails to wrap reference to object of abstract class
727374 std::exception_ptr only partially comparable to null
729760 std::async fails compilation for Callable with two or more arguments.
730454 Emulation of variadic templates in C++11 standard library does not work
732529 std::result_of not working with functors
733204 std::map Debug Visualisers not working for vs2011
733222 Compiler error on <mutex>:304
733729 debug assertion "string subscript out of range" is incorrect for [size()]
734888 shared_ptr in unordered_set
735224 VS2011 Beta fires assertion about unlocking of unowned mutex
735731 std::async(std::launch::async, ...) does not behave as std::thread(...)
735732 STL Vector of Vector Insertion Problem
735875 Wrong output in std::put_time
736356 No more than two arguments can be passed to <future> : async.
736924 Packaged task & thread compile error bug
737812 std::thread does not accept std::move
738919 std::locale::global() / std::locale() thread-safety issue
739016 std::make_shared call error (c++)
742642 Ambiguous use of the overloaded function std::string to_string(int val);
742856 BUG with std::async ?
742965 Operator < incorrect for tuples with more members than _VARIADIC_MAX
745614 <system_error>: error C2382 when compiling with '/Za' (Disable Language Extensions)
745643 error C2382 on "std::generic_category", "std::iostream_category", "std::system_category"
745967 Compiler Error C2382 with Standard Header File <system_error> in Visual C++ 2012 RC

A few notes on various arcane topics:

This list of 127 bugs consists of all of the bugs that I could find in our "old database" and "new database" (we use Team Foundation Server for bug tracking and version control, but we switched TFS databases a couple of years ago, making archaeological expeditions "fun") which were created by Connect, filed against the C++ Standard Library, resolved by me as Fixed, and fixed between VC10 SP1 and VC11 RTM.  It's reasonably comprehensive, but it might not be absolutely exhaustive.  I have intentionally excluded all non-Connect bugs (the grand total of fixed bugs found by Connect, myself, and other MS employees is roughly 330 - and that doesn't count things that were really bugs but never tracked as such) and private Connect bugs (a few people who file Connect bugs mark them as private, which prevents the world from seeing them - I recommend against doing this unless the bug's repro somehow contains information that you don't want the world to see).  Additionally, I have made no attempt to group bugs resolved as fixed that are actually duplicates (e.g. the many uniform_int_distribution bugs, fixed by a comprehensive rewrite).

I have presented the bugs' original titles from their submitters, although they're often renamed internally.  This is almost never interesting (there is a certain format that I like, so my bugs sort nicely), but I can share one exception.  Connect#533464 arrived as "The <initializer_list> header in the VC10 release candidate".  I improved this to "<initializer_list>: Zombie header hungers for our delicious brains".  (In VC10, I screwed up by leaving a nonfunctional <initializer_list> header in the product.)

Finally, you may be wondering where all of these bugs come from.  (I take all STL bugs personally, and I'd hate for someone to see this list and go around thinking "wow, the STL sure is buggy".)  Our STL implementation is very solid, but it is also very large and must deal with an enormous variety of complicated situations.  C++11 churn has led to two categories of bugs: those where the Working Paper said something bogus at the time that we implemented it (e.g. this happened with to_string(), bitset, and async()), and those where it permits more complicated inputs than we've had to deal with before (typically rvalue references and movable-only types).  Totally new features (e.g. atomics/threads/futures) arrive with totally new bugs.  There's the perennial gotcha of users doing "weird stuff" (e.g. obscure compiler switches like /J and /vd2).  And because the STL has no control over how demanding its users' performance requirements are, things that would be evil premature optimizations in ordinary application code are treated as totally legitimate performance bugs in the STL.  (A number of micro-optimizations in vector were suggested by a user and implemented in VC11, for example.)

The bottom line is that we're continuously improving the STL, so you should always upgrade to the latest major version and service pack as soon as possible - and that reporting bugs through Microsoft Connect really helps.

Stephan T. Lavavej
Senior Developer - Visual C++ Libraries
stl@microsoft.com

 

Announcing Casablanca refresh

$
0
0

Back, at the end of April, we announced our first release of Casablanca as an incubation project on Devlabs. Since then, we are glad to have received a positive response from the C++ community.

 

Today, we are announcing a “bug-fix” refresh to the Casablanca release. The update can be downloaded from the Casablanca devlabs site.

The notable additions are:

  • A number of bug fixes (including some reported by you)
  • Support for https on the client
  • Support for Visual Studio 2012 RC, Azure SDK 1.7 and Windows 8 Release Preview

 

Please use the devlabs forums to provide us with feedback.

 

Thank you for your support and we look forward to hearing back from you.

 

The Casablanca Team.

Optimizing your binaries with the VC++ compiler for optimum performance (Feedback Requested)

$
0
0

There are several reasons to program in C++, and one of the most important ones is the incredible performance that one can obtain. 

There are a set of optimizations that the Microsoft Visual C++ compiler offers to perform on your binaries to yield the best performance for your application on varying hardware (for e.g. via compiler switches such as /O2, Profile-Guided Optimization (PGO) and Link-Time Code Generation (LTCG) etc.). 

We are reaching out to you to get your feedback on the optimizations the compiler offers today and other potential optimizations that we can introduce to help get better performance from your application.

Please take a few minutes to complete this survey. Your answers to this survey will help us make the right investments for future releases of Visual Studio. Completing this questionnaire should take about 20
minutes to finish. 

Thanks in advance for taking the time! 

Thanks,

Code Generation and Optimization team

Debugger Type Visualizers for C++ in Visual Studio 2012

$
0
0

 In Visual Studio 2012, one of the new features for C++ developers is the new native type visualization framework (natvis) added to the debugger which allows customizing the way data types are displayed in debugger variable windows (e. g. autos, watch, locals, and data tips). For those who are familiar with the autoexp.dat file that has been used in earlier versions of Visual Studio, this new visualization framework supersedes that and offers xml syntax, better diagnostics, versioning and multiple file support.

To illustrate how type visualizers help make it easier to inspect objects, the following screenshot shows how a std::vector<int> is displayed in the debugger without any type visualizers:

                   ![if>

The view without type visualizers is not user-friendly and hard to read. You cannot easily see the size or the elements of the vector. Visual Studio ships with type visualizers for common data types such as std::vector and the default view for a std::vector using type visualizers is much more useful:

  ![if>

 

Creating a type visualizer for a custom data type

If you have a custom data type you can easily override Visual Studio’s default view of it using this framework and make it easy to inspect objects of that type. To demonstrate how you can do this, let’s go through the process of creating one for the simple rectangle type shown in the code snippet below (the dummy code that uses it is also included):

struct Rectangle

{

    int height;

    int width;

};

 

int _tmain(int argc, _TCHAR* argv[])

{

    Rectangle myRectangle = { 3, 4 };

    Rectangle myRectangle2 = { 4, 4 };

    return 0;

}

 

The debugger’s default view of the “myRectangle” variable which we are going to customize is as follows:

 

  ![if>

Type visualizers for C++ types are specified in .natvis files. A natvis file is simply an xml file (with .natvis extension) that contains visualization rules for one or more types. At the start of each debugging session, Visual Studio processes any natvis files it can find in the following locations:

  • -         %VSINSTALLDIR%\Common7\Packages\Debugger\Visualizers (requires admin access)![if>
  • -         %USERPROFILE%\My Documents\Visual Studio 2012\Visualizers\![if>
  • -         VS extension folders ![if>

 

As the first visualizer for the rectangle type, create a new file called “rectangle.natvis” containing the following xml (explained further below) and save it in “My Documents\Visual Studio 2012\Visualizers” folder.

 

<?xml version="1.0" encoding="utf-8"?>

<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">

    <Type Name="Rectangle">

        <DisplayString>A rectangle with height = {height} and width = {width}</DisplayString>

    </Type>

</AutoVisualizer>

 

After the file is saved, start debugging the code snippet we have for the type and view the ‘myRectangle’ variable in the watch window. The debugger now displays the object as:

 

  ![if>

 

To explain the xml snippet in the natvis file, each Type element represents a visualizer entry for a type whose fully qualified name is specified in the Name attribute. DisplayString element customizes the string shown in the value column for the type. It accepts a mixture of arbitrary strings and expressions. Everything inside curly braces ({height}, {width} above) is interpreted as an expression and gets evaluated by the debugger.

Let’s assume you would like to enhance this view when the rectangle is actually a square and display something different. You can use the Condition attribute, which is available for many visualizer elements, to have if-else logic in the visualization entry. Add the following highlighted line to the visualizer entry and save the file:

<?xml version="1.0" encoding="utf-8"?>

<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">

    <Type Name="Rectangle">

        <DisplayString Condition="height == width">This is a square with sides of {height}</DisplayString>

        <DisplayString>This is a rectangle with height = {height} and width = {width}</DisplayString>

    </Type>

</AutoVisualizer>

 

Note that it is NOT necessary to restart Visual Studio for it to pick up the changes to a visualizer. Once you start the debugger and add ‘myRectangle’, ‘myRectangle2’ variables to the watch window, you can see a different string is shown for a rectangle object that is actually a square:

 

 ![if>

Just as you can customize the value of the variable shown in the value column, you can also customize the view of the child elements when the variable is expanded in the debugger windows. Let’s say you would like to see the area of a rectangle in addition to its height and width during debugging. The Expand node, which allows you to define child elements for a type, can be used for this purpose. Add the highlighted section below to the visualizer entry and save the file:

<?xml version="1.0" encoding="utf-8"?>

<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">

    <Type Name="Rectangle">

        <DisplayString Condition="height == width">A square with sides of {height}</DisplayString>

        <DisplayString>A rectangle with height = {height} and width = {width}</DisplayString>

        <Expand>

            <Item Name="height">height</Item>

            <Item Name="width">width</Item>

            <Item Name="area">height * width</Item>

        </Expand>

    </Type>

</AutoVisualizer>

 

As you can guess, each Item node defines a single child element whose name is given by the Name attribute and whose value is given by the expression in the node text. This is the updated view with the area element added:

  ![if>

More information

This blog post covers just a little bit of what you can do with the new native type visualization framework in the Visual Studio debugger. To learn more about it you can check out our sample page on msdn where we have more examples, xml syntax reference, instructions on turning on diagnostics and deploying visualizers via VSIX packages.

 

  ![if>

Cagri Aslan, Developer on the Visual Studio Debugger team.

Template Argument Deduction - Core C++, Part 2

$
0
0

Part 2 of my third video lecture series (covering the C++ Core Language) is now available.  In this part, I took an hour to explore template argument deduction, including what "non-deduced contexts" are - and how they can be used to your advantage!  For reference, here are all of the links to my video lectures, plus my GoingNative 2012 presentation:

 

[STL Introduction]

Part 1 (sequence containers)

Part 2 (associative containers)

Part 3 (smart pointers)

Part 4 (Nurikabe solver) - see Wikipedia's article and my updated source code

Part 5 (Nurikabe solver, continued)

Part 6 (algorithms and functors)

Part 7 (algorithms and functors, continued)

Part 8 (regular expressions)

Part 9 (rvalue references)

Part 10 (type traits)

 

[Advanced STL]

Part 1 (shared_ptr - type erasure)

Part 2 (equal()/copy() - algorithm optimizations)

Part 3 (_ITERATOR_DEBUG_LEVEL, #pragma detect_mismatch, and /d1reportSingleClassLayout)

Part 4 (rvalue references v2.1 and associative container mischief)

Part 5 (deduplicator, using Boost.Bimap, Filesystem, and ScopeExit) - see my deduplicate.cpp

Part 6 (container pretty printer) - see my pretty_printer.cpp

 

[GoingNative 2012]

STL11: Magic && Secrets (make_shared<T>(), emplacement, pair SFINAE, range-based for-loop) - see my slides

 

[Core C++]

Part 1 (name lookup)

Part 2 (template argument deduction)

 

Stephan T. Lavavej

Senior Developer - Visual C++ Libraries

stl@microsoft.com

Compiler Bugs Fixed In Visual Studio 2012

$
0
0

Following STL Bugs Fixed In Visual Studio 2012, here are similar lists for the compiler front-end (responsible for parsing C++)...

ID Title
599151 Using declaration for a name of a type does not work in MS C++ compilers
603872 Support for XML Documentation in native C++ code
611359 C++ compiler: Temporary object created when it should not, thus making code that worked in VC9 not work anymore!
611716 C++/CLI class static constructor not called in release build
612158 Illegal C++ fails to generate C2039 error, allowing buffer overrun
619198 [c++] Compiler fails to deduce template parameter.
623481 Compiler crash
624283 Private copy operator vs __declspec(dllexport)
624378 Can I double&& in template
624757 Incorrect function template deduction involving pointor to member data
625710 Compilation error in case of repeating forward declaration within class
629060 Compiler Crash related to System.Core and String^
629262 C/C++ Optimizing Compiler has stopped working - System.Core and String^ related
629931 Internal compiler error C1001 when compiling OpenCV 2.1/2.2 with C++/CLI 64 bit
632850 VC++ 2010 Line Number Wrapping
633274 C++ compiler allows use of unspecialized member function template
633782 C++ #pragma secion doesn't allow read,write,execute
634671 Bug with operator overloading and nested lambdas
634688 Wrong return type when running nested lambda
634966 Argument dependent lookup chooses the wrong function inside sizeof statements
636634 Unexpected error C2751 reported at 'using namespace' directive inside a lambda expression.
640228 compiler template declaration/definition mismatch error
640281 C++/CLI compiler crashes when attempting to compile event System::EventHandler<>;
641023 Inner lambda capture list can't see variable through auto-capture of outer lambda, thus rendering the name unknown to the inner capture list
641032 Lambda's automagic ctor gets wrong signature (or call) when implicit and explicit capture is mixed.
644190 Unexpected error C2871 reported at 'using namespace' directive before a lambda expression
649898 VC10 STL: std::pair template constructors ignore if elements are implicitly constructable or not
649953 Incorrect code generated when returning struct by value and compiling for x86.
650667 Incorrect IDE error
651255 C++ CLI property overriding and renaming
651762 Incorrect deduction when taking the address of an instantiated member function template using a template type
651972 Visual C++: Copy Constructor Bug for Base Class with Template Constructor
652743 default constructors of __declspec(selecany) variables not called
657040 Buggy static_assert
661294 Wrong "this" pointer when using templates in C++ and targeting x64 Platform
663659 Large arrays with const size can crash at run-time on win64
663884 VC10: weird template deduction error with non-type default template argument
663904 Compiler fails to compile inner struct/class/union in a namespace after some forward declarations
665425 C1001 Error - "virtual" inheritance, member function pointer template and "Enable minimal rebuild"
667226 private template operators in C++ treated as public
669549 [C++] Temporary strings implicitly constructed take l-value path instead of r-value path
674672 Callee disassembly expects address which caller is not providing in x64 mode
674867 static_assert failure does not trigger a compilation error
674944 C++/CLI compiler gives error C3214 when invoking a class with generic constraint
676125 Public Parameterless Constructor Not Found in VC++
679716 Bug in VC++ 2010 with global refence to array
681998 C++: member rvalue references are initialized with erroneous copies in constructor initializer list
682454 Compiler bug - cannot access private member declared in class
682688 [C++] Failure to compile functions taking template template arguments of dependent types
682689 [C++] No warning when returning r-value-references to locals / temporaries
682695 [C++] __alignof() fails to properly evalute alignment of dependent types
684807 template template parameters don't work with unions
684953 miscompilation of aggregate initializer with lambdas inside
687344 Lambda ICE
687345 Local class and lambda
687903 VC++ 2010 Compiler Crash when using properties (__declspec(property..) and /doc option
687931 cl.exe crashes with a message box compiling some specific code
687935 Ambiguous call to overloaded function in c++ when using lambdas
688106 Fatal Error C1001
688107 C2466 emitted twice for the same construct
688198 Invalid error error C2871 when using functions defined within nested namespaced in lambdas.
688443 C2143 emitted twice for the same construct
689504 C2326 on Lambdas with [this]-Capture
689815 std::result_of not working with lambdas
690955 C4673 Compiling Exception Hierarchy Using Virtual Multiple Inheritence
693671 Compile Error in globally scoped lambda with a for loop
694857 Bug in lambda expressions
696310 C2027 emitted multiple times compiling deque with an incomplete stored class
696412 Compiling local static auto object causes internal compiler error
697006 VC++ cannot resolve function overload as template parameter
697086 C4430 emitted twice for the same construct
697512 Internal compiler error while compiling specific initializer of global object.
698148 C4743 warning on explicit call of a templated function
699236 Visual C++ does not handle based enums correctly
699543 Internal compiler error in CL.exe
703088 Cannot call static member functions of template types directly from lambdas in C++.
704352 The function pointer types estimated by template are wrong
704955 Cannot directly return with decltype
706537 compile error C2663 in lambda, if boost 1.48 posix_time.hpp is included.
708011 Compiling trivial boost::property_tree test gives fatal error C1001
711056 D8030: INTERNAL COMPILER ERROR
712925 error C2563: mismatch in formal parameter list
712990 bad warning using negative value for enum with underlying type specified as signed short
713679 Unexpected behaviour of this capture in a lambda expression
714524 illegal use of local type in template instantiation
714628 Argument Dependent Lookup Failure in Visual C++ 2010
716461 const data member triggers dynamic initialization with C++ compiler
717318 Incorrect parsing of pointer to array return types in trailing return type template functions
717474 Unterminated __asm blocks cause memory exhaustion for compiler
718050 Warning C4355: 'this' : used in base member initializer list
718578 [C++] Reference default argument falsely converted to pointer on instantiation of more than 2 explicit specializations
718621 VC++10 crashing on basic BOOST_TYPEOF usage
719083 C++ compiler - decltype doesn't infer the correct return type - vector<int>& instead of vector<int>.
719275 Visual C++ compiler won't accept a function pointer as a templated rvalue reference parameter
720670 Failed to compile program using boost::program_options and lambda expression
724314 T const & cannot receive char[]
724319 decltype can generate references of zero sized array
724362 unable to match function definition
724616 Absence of conversion operator-function to pointer to function in lambda-expression.
725134 Nested lambda expressions can not capture entities of enclosing lambda expressions
725189 decltype deduces wrong type
725876 Rvalue reference overloading rules
726039 error C2914: 'foo' : cannot deduce template argument as function argument is ambiguous
727873 VC 11 optimizing compiler crash
728349 VS11 Beta - fatal error C1001
728741 Auto type deduction gets confused for multiple variables
730244 Reference capture by inner lambda of by-value captured variable of non-mutable outer lambda causes weird compiler error
730538 Out-of-line method definition in template specialization
732063 decltype expressions involving polymorphic callable entities fails in VC++11 Beta but works in VC++10
733475 Impossible value-initialization with decltype
734023 ICE (compiler crash), probably related to try-catch in lambda
734303 Lambda-to-function-pointer conversion fails in nested lambdas.
734791 /Za (disable extensions) disables template arguments with local linkage, which is a C++11 feature.
735254 An internal compiler error reduced to a small code snippet
735274 Enumeration can not be captured into a lambda function
735281 Nested lambdas can not refer to outer types
736295 Incorrect name lookup in a lambda expression defined inside a class member function
736576 The explicit capture of an entity by a nested lambda-expression does not cause its implicit capture by the containing lambda-expression.
736647 Internal Compiler Error with boost::property_tree::ptree.get_child()
736931 internal compiler error instead of compiler diagnostic
736965 Friend Template Classes and Lambda Functions
738324 Separated declaration and definition of a template function using template-of-template does not compile
739900 internal compiler error
743026 decltype appears to drop const qualifiers for overloaded operators
744323 Impossibility of using typename with storage class specifier static in lambda expressions
750224 Visual Studio 2010, compiler crash
751729 range-based for and shared_ptr internal error

... and the compiler back-end (responsible for optimizing and generating assembly code):

ID Title
526921 VS2008 C++ x64: buggy result in expression containing double and unsigned int64
555266 C++ compiler generates wrong code with optimization flag /O2
565435 Linker crash with no unusual settings
566543 Bad code generation for SSE/x64 release
577724 Vs2010 x64 C and C++ program crashes when string literal are not modified
581207 Visual Studio 2005 SP1 reproducible linker error (LKN1257 caused by C1083)
581208 inlining code produces bug
582063 Compiler Bug when generating data.
587106 A false C4701 bothers me under a certain condition.
589084 Optimizer bug in Visual C++ Express Edition 2010 (Version 10.0.30319.1 RTMRel)
591804 Useless C++ C4700 warning for x64 Release builds
596345 avx 256 bit intrinsics bug when compile in 64 bit
596828 #pragma comment(lib) should be able to take relative paths from additional lib dirs
597862 DIA SDK dia2dump sample coding mistake prevents dumping of enum and typedef information
606013 OpenMP Release x64 crash in critical section
608187 VS2008 amd64 link error (LNK1103) when using /openmp and /GL flags
612671 [VC2010] Alignment issue with _mm256_store_si256() AVX intrinsic in 64-bit debug builds
613573 VC++2010 Optimize gen infinite-loop exe ...
613868 C++ optimizer fails in debug with /O2 and /Zi
615374 Global variables of __m128i type behave incorrectly with global optimization.
616129 cl.exe: fatal error C1001 when using /O2 switch
623280 Internal compiler error (x86, O2)
624668 (C++ x86) /Og renders function parameters in catch blocks unusable
626399 Possible optimization bug on manual bounds checking
629550 Bug in C++ compilation for structures compiled with pragma pack (1)
634020 Crash when compiling [related to float/double conversions?]
634223 OpenMP & C++ optimization crashes - incorrect program transform/optimization?
634455 Incorrect shift left/right optimization
634606 Compiler bug with SSSE3
641144 LLVMX86Disassembler fails to compile properly in optimize mode
643764 C++ optimization bug; incorrect assembly emitted
644615 Wrong comparison instruction selected for loop preamble
646489 Unaligned data access optimzed away
646911 Bad value in EDI causing a crash when executing MASKMOVDQU
647064 Incorrect code generation when optimizing and using SSE2
650228 optimization bug
650346 C optimization bug
653501 Incorrect shift optimization
653771 _mm256_castps128_ps256 does unaligned read
657966 VS2010: x64 compiler optimization bug (crash)
658197 Build Error when enable both Incremental Linking and Generate Map File when rebuild it.
658441 Database Error _ it's back
661810 Compiler bug for 64-bit release?
664827 application crashed when include fstream in mixed (Cli/native) c++ project
665896 link1104 cannot open .map file issue.
666704 Visual C++ generates incorrect code with omit frame pointer and setjmp
668324 Linker internal error/crash for x64 OpenMP
672163 Incorrect code generated when adding array of 4 char to array of short in a loop
675274 Link 1000 error when compiling using 64bit and release (any optimization) build
676417 Bug in cl for x64 (c compiler)
676584 bug in cl (c compiler)
676931 Invalid C code result with optimization
677627 Linker - A repeated import table under a different dll.
678200 VC++2010 ignores side effects when skips initialization of unused variables
678524 Optimization bug in x64 compiler when left shifting 64-bit value
678710 Compiler crash on _InterlockedCompareExchange64
681524 Visual C++: Global Variables Crash Edit-and-Continue
683152 Wrong Release-code generation for SSE4 intrinsics
683557 Symbol not found in code block with float ops
684087 load imm8 with data from gpr
687527 Code optimizer fails to eliminate memcpy/memset when "number of bytes" is zero
688139 Visual Studio 2010 SP1 Release x64 /O2 optimization bug (c2.dll version 10.00.40219.1 amd64)
688755 Incorrect vectorized cast from float to unsigned int
690107 Disassembly window shows seriously messed up mapping of source code onto machine code
690294 Bad instruction re-ordering causes crash in code generated by MSVC 2010
691217 Inline assembler assembles ARPL instruction incorrectly
691685 Regression: MDA FatalExecutionEngineError (with repo) calling release x32 managed c++ lib, but ok with x64 and x32 debug version.
692745 Code optimizer fails to detect sequential writes to adjacent parts of the same array
693222 Code optimizer emits prologues/epilogues calls when unreachable code manipulating std::vector is present
694100 Slow compilation of 'large' amounts of data (objects/arrays) with references
694755 Missing AVX intrinsics
696041 std::WhateverContainer::iterator::operator->() invokes overloaded "operator&()" of the contained type
696766 VS2010 C++ wrong subtraction result (1.0f - 1.0f == 1753.0) when code optimization is on
698296 Optimization flag -O2 issue in C/C++ compiler
699728 Visual Studio runs out of memory when compiling recursive inline templates in Release
700279 Bug in Visual Studio 2010 SP1 C++ compiler
711698 Linker doesn't rebuild when stack reserve changed
713927 VS 2010 Debugger breakpoint skips first iteration of for-loop
715034 VS2010 C++ compiler generates incorrect code in full optimise /Ox /Ob1
717690 Feedback: 32-bit Development PCs build print drivers in half the time compared to 64-bit PCs (16 vs. 32 mins)
719105 C++ compiler optimization: /fp:fast fails to honour cast from single to double in x64
720646 VC2010 bug with optimization of bit-shift operator
722313 VS11 build/lib.exe will not allow the creation of c++ static library that calls WinRT apis (with 8175 & BETAREL)
722366 IDiaEnumSymbolsByAddr::Next doesn't return huge PDB
723548 VS11DP linker outputs LINK messages in chinese language, in VC++ solutions, for specific source code.
723805 VS2010 C++ compiler produces incorrect code in release mode.
727519 Intrinsics problem
728165 VS 11 Beta does not build static library with WinRT calls in source code (compiled with /Zw)
728802 pdbcopy tool that comes with SDK only works on x32 platforms
729108 VC++ 11 compiler Bug in 64 bit application, optimization resulting in incorrect behaviour (shl)
729496 ml64.exe output wrong code for "vpsrld xmm, xmm, xmm"
729606 MASM crashes due to an internal error.
729818 For loop Error
730417 Internal Compiler Error when compiling EigenSolver
730747 Loop unrolling bug
731193 Compiler Bug in Optimize Release Mode 64bit.
731270 vc++ shift produces inconsistent result
732925 Optimization bug with recursive functions
733810 compiler bug with __m128i
735523 Miscompile with RVO in x64 compiler
735861 fatal error C1001
737430 MS DIA get_virtualAddress for static const class member
738595 Built application crashes on exception rethrow
738878 LOCK prefix encoded by masm to an invalid instruction (causing #UD)
739798 Incorrect code generation for __restrict keyword with full optimization
740143 C/C++ compiler crashes on simple code
740487 "Maximize speed" creates incorrect code
740847 error LNK2019: unresolved external symbol __isa_available
740985 C++ VS2010: bug in generating optimized code with a loop
741370 arm_neon.h header errors and typos
742715 Internal error has occured in the compiler when compling opencv_lapack
744341 fatal error C1001: An internal error has occurred in the compiler in C++11 construction "for (int n : <temp object>)"
746862 Native edit-and-continue not working in VS2012 RC
746946 Compiler produces wrong IL code for managed c++ (only release compile) VS2010 SP1
749567 Visual Studio 2012 RC compiler crashes with /Ox & /fp:fast options

As usual, these lists are far from exhaustive.  They don't contain private Connect bugs or non-Connect bugs (which come from many sources: compiler testers, STL maintainers with last names ending in J, other MS teams like Windows and Office, external customers with support contracts, etc.).  Also, some public Connect bugs aren't represented here (in particular, /analyze and /ZW bugs).

If you find any more bugs that have eluded us, please continue to report them through Microsoft Connect.

Stephan T. Lavavej
Senior Developer - Visual C++ Libraries


Visual C++ in Visual Studio 2012

$
0
0

If you have read Jason Zander’s post earlier today, you know that Visual Studio 2012 has been released to the web! Check out the MSDN Subscriber Download Page  and the Visual Studio product website. This release has brought a huge amount of new value for C++ developers. Here are the highlights:

  

C++11 Standards Support

Language Support

  • Range-based for loops. You can write more robust loops that work with arrays, STL containers, and Windows Runtime collections in the form for ( for-range-declaration : expression ).
  • Stateless lambdas, which are blocks of code that begin with an empty lambda introducer [] and capture no local variables, are now implicitly convertible to function pointers as required by the C++11 Standard.
  • Scoped enumerations support. The C++ enum class enum-key is now supported. 

Standard Template Library

  •  We’ve added support for the new STL headers: <atomic>, <chrono>, <condition_variable>, <filesystem>, <future>, <mutex>, <ratio>, and <thread>.
  •  SCARY iterators. As permitted but not required by the C++11 Standard, SCARY iterators have been implemented.

Here is the detailed discussion on C++ 11 features in Visual Studio 2012, with links to the corresponding C++ 11 specs. Please also see the fun video series on STL … by STL.

  

Parallel Programming

Compiler and Linker

We’ve made major investments to help developers make the most of their target hardware. We are introducing the auto-vectorizer to take advantage of SSE2 instructions to make your loops go faster by doing 4 number operations at time, auto-parallelizer to automatically spread your work on many CPUs, and C++ AMP (C++ Accelerated Massive Parallelism) to leverage the power of GPU for data parallel algorithms. Note that C++ AMP also comes with a first-class debugging and profiling support.

Libraries (PPL)

We continue to enhance the breadth and depth of Parallel Patterns Libraries (PPL). In addition to major investments in async programming, we’ve added more to algorithms and concurrent collections. We are also working very hard in bringing most of these concepts into the next revision of the C++ standard.

Debugging

In addition to the Parallel Tasks window and Parallel Stacks window, Visual Studio 2012 offers a new Parallel Watch window so that you can examine the values of an expression across all threads and processes, and perform sorting and filtering on the results.

  

C++ for Windows 8

Note: XAML/DirectX interop :Developers targeting Windows 8 Store apps can use both XAML and DirectX in the same app, which allows developers to build flexible user interfaces like the one in FreshPaint app.


  

IDE

In addition to the general Visual Studio IDE improvements like the new Solution Explorer, Preview Tabs, new Find, Compare, and Asynchronous Solution Load etc., we’ve made several IDE enhancements that are new for C++ and help C++ developers be more productive with Visual Studio.

  • C++ Code Snippets. The IDE now adds the skeleton code for common C++ code constructs like switch, if-else, for loop, etc. automatically. Select a code snippet from the List Members drop-down list to insert it into your code and then fill in the required logic. You can also create your own custom code snippets for use in the editor.
  • Semantic Colorization. C++ code editor now conveys semantic structure of the code by colorizing types, enumerations, macros, and other C++ tokens by default. There are a number of other tokens that can be colorized differently to customize the experience.
  • IntelliSense Enhancements. The List Members drop-down list appears automatically as you type code into the code editor. Results are filtered using a fuzzy search algorithm, so that only relevant members are displayed as you type. C++ IntelliSense Quick Info tooltips now show richer XML documentation comments style information. Selecting a symbol now highlights all instances of the symbol in the current file. Press Ctrl+Shift+Up Arrow or Ctrl+Shift+Down Arrow to move among the highlighted references.

 

  • C++/CLI IntelliSense. C++/CLI now has full IntelliSense support. IntelliSense features such as Quick Info, Parameter Help, List Members, and Auto Completion now work for C++/CLI. In addition, the other IntelliSense and IDE enhancements listed in this document also work for C++/CLI.
  • Visual Studio Templates support. You can now use the Visual Studio Templates technology to author C++ project and item templates

  

Application Lifecycle Management Tools (ALM)

Code Analysis

Static code analysis helps identify runtime issues at compile time when they are much cheaper to fix. Code analysis for C++ feature in Visual Studio 2012 has been enhanced aiming to provide improved user experiences as well as analysis capabilities. In this new version, code analysis has been extended to support 64 bit apps, ship with additional concurrency rules to detect issues like race conditions, and offer the ability for creating customized rule sets. This feature is now available in all Visual Studio editions allowing every developer to make the best use of it.

Architecture Dependency Graphs

Generate dependency graphs from source code to better understand the architecture of your existing apps or code written by others. In Visual Studio 2012 you can generate dependency graphs by binaries, classes, namespaces, and include files for C++ apps. Also, use Architecture Explorer tool window to explore the assets and structure of your solution by looking at solution view or class view.

Example: Dependency Graph by Binary

Example: Dependency Graph by Include Files

Use Architecture Explorer to browse assets in the solution

 

Unit Test Framework for C++

Visual Studio 2012 ships with a new unit test framework for native C++. You can write light-weight unit tests for your C++ applications to quickly verify application behaviors. Use the new Test Explorer tool window to discover and manage your tests along with test results. This feature is now available in all Visual Studio editions.


Code Coverage

Code coverage has been updated to dynamically instrument binaries at runtime. This lowers the configuration overhead, provides better performance and enables a smoother user experience. Code coverage feature has also been integrated well with the new C++ unit test framework in Visual Studio 2012 allowing you to collect code-coverage data from unit tests for C++ app by one single click within Visual Studio IDE.


  

 

Coming Soon!

We’ve announced two things that will arrive in a few months:

 

C++ for Windows Phone 8

As soon as the Windows Phone 8 SDK is made available, C++ developers will be able to target Windows Phone. Stay Tuned!

Example: Windows 8 Marble Maze Sample targeting Windows Phone 8

 

As always, we love hearing from you. Thanks for keeping us honest and kudos to those who have influenced our product design for the better!

 

On behalf of the VC++ team,

Rahul V.Patil

Lead Program Manager, C++

 

Connecting C++ and XAML

$
0
0

Hi, I’m Andy Rich, a tester on the C++ frontend compiler and one of the primary testers of the C++/CX language extensions.  If you’re like me, making use of a technology without understanding how it works can be confusing and frustrating.  This blog post will help explain how XAML and C++ work together in the build system to make a Windows Store application that still respects the C++ language build model and syntax.  (Note: this blog post is targeted towards Windows Store app developers.)

The Build Process

From a user-facing standpoint, Pages and other custom controls are really a trio of user-editable files.  For example, the definition of the class MainPage is comprised of three files: MainPage.xaml, MainPage.xaml.h, and MainPage.xaml.cpp.  Both mainpage.xaml and mainpage.xaml.h contribute to the actual definition of the MainPage class, while MainPage.xaml.cpp provides the method implementations for those methods defined in MainPage.xaml.h.  However, how this actually works in practice is far more complex.


 

This drawing is very complex, so please bear with me while I break it down into its constituent pieces.

Every box in the diagram represents a file.  The light-blue files on the left side of the diagram are the files which the user edits.  These are the only files that typically show up in the Solution Explorer.  I’ll speak specifically about MainPage.xaml and its associated files, but this same process occurs for all xaml/h/cpp trios in the project.

The first step in the build is XAML compilation, which will actually occur in several steps.  First, the user-edited MainPage.xaml file is processed to generate MainPage.g.h.  This file is special in that it is processed at design-time (that is, you do not need to invoke a build in order to have this file be updated).  The reason for this is that edits you make to MainPage.xaml can change the contents of the MainPage class, and you want those changes to be reflected in your Intellisense without requiring a rebuild.  Except for this step, all of the other steps only occur when a user invokes a Build.

Partial Classes

You may note that the build process introduces a problem: the class MainPage actually has two definitions, one that comes from MainPage.g.h:

 partial ref class MainPage : public ::Windows::UI::Xaml::Controls::Page,
      public ::Windows::UI::Xaml::Markup::IComponentConnector
{
public:
  void InitializeComponent();
  virtual void Connect(int connectionId, ::Platform::Object^ target);

private:
  bool _contentLoaded;

};

And one that comes from MainPage.xaml.h:

public ref class MainPage sealed
{
public:
  MainPage();

protected:
  virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
};

This issue is reconciled via a new language extension: Partial Classes.

The compiler parsing of partial classes is actually fairly straightforward.  First, all partial definitions for a class must be within one translation unit.  Second, all class definitions must be marked with the keyword partial except for the very last definition (sometimes referred to as the ‘final’ definition).  During parsing, the partial definitions are deferred by the compiler until the final definition is seen, at which point all of the partial definitions (along with the final definition) are combined together and parsed as one definition.  This feature is what enables both the XAML-compiler-generated file MainPage.g.h and the user-editable file MainPage.xaml.h to contribute to the definition of the MainPage class.

Compilation

For compilation, MainPage.g.h is included in MainPage.xaml.h, which is further included in MainPage.xaml.cpp.  These files are compiled by the C++ compiler to produce MainPage.obj.  (This compilation is represented by the red lines in the above diagram.)  MainPage.obj, along with the other obj files that are available at this stage are passed through the linker with the switch /WINMD:ONLY to generate the Windows Metadata (WinMD) file for the project. This process is denoted in the diagram by the orange line.  At this stage we are not linking the final executable, only producing the WinMD file, because MainPage.obj still contains some unresolved externals for the MainPage class, namely any functions which are defined in MainPage.g.h (typically the InitializeComponent and Connect functions).  These definitions were generated by the XAML compiler and placed into MainPage.g.hpp, which will be compiled at a later stage.

MainPage.g.hpp, along with the *.g.hpp files for the other XAML files in the project, will be included in a file called XamlTypeInfo.g.cpp.  This is for build performance optimization: these various .hpp files do not need to be compiled separately but can be built as one translation unit along with XamlTypeInfo.g.cpp, reducing the number of compiler invocations required to build the project.

Data Binding and XamlTypeInfo

Data binding is a key feature of XAML architecture, and enables advanced design patterns such as MVVM.  C++ fully supports data binding; however, in order for the XAML architecture to perform data binding, it needs to be able to take the string representation of a field (such as “FullName”) and turn that into a property getter call against an object.  In the managed world, this can be accomplished with reflection, but native C++ does not have a built-in reflection model.

Instead, the XAML compiler (which is itself a .NET application) loads the WinMD file for the project, reflects upon it, and generates C++ source that ends up in the XamlTypeInfo.g.cpp file.  It will generate the necessary data binding source for any public class marked with the Bindable attribute.

It may be instructive to look at the definition of a data-bindable class and see what source is generated that enables the data binding to succeed.  Here is a simple bindable class definition:

[Windows::UI::Xaml::Data::Bindable]
public ref class SampleBindableClass sealed {
public:
  property Platform::String^ FullName;
};

When this is compiled, as the class definition is public, it will end up in the WinMD file as seen here:

This WinMD is processed by the XAML compiler and adds source to two important functions within XamlTypeInfo.g.cpp: CreateXamlType and CreateXamlMember.

The source added to CreateXamlType generates basic type information for the SampleBindableClass type, provides an Activator (a function that can create an instance of the class) and enumerates the members of the class:

if (typeName == L"BlogDemoApp.SampleBindableClass")
{
 XamlUserType^ userType = ref new XamlUserType(this, typeName, GetXamlTypeByName(L"Object"));
  userType->KindOfType = ::Windows::UI::Xaml::Interop::TypeKind::Custom;
  userType->Activator = 
   []() -> Platform::Object^
   {
     return ref new ::BlogDemoApp::SampleBindableClass();
   };
  userType->AddMemberName(L"FullName");
  userType->SetIsBindable();
  return userType;
}

Note how a lambda is used to adapt the call to ref new (which will return a SampleBindableClass^) into the Activator function (which always returns an Object^).

From String to Function Call

As I mentioned previously, the fundamental issue with data binding is transforming the text name of a property (in our example, “FullName”) into the getter and setter function calls for this property.  This translation magic is implemented by the XamlMember class.

XamlMember stores two function pointers: Getter and Setter.  These function pointers are defined against the base type Object^ (which all WinRT and fundamental types can convert to/from).  A XamlUserType stores a map<String^, XamlUserType^>; when data binding requires a getter or setter to be called, the appropriate XamlUserType can be found in the map and its associated Getter or Setter function pointer can be invoked.

The source added to CreateXamlMember initializes these Getter and Setter function pointers for each property.  These function pointers always have a parameter of type Object^ (the instance of the class to get from or set to) and either a return parameter of type Object^ (in the case of a getter) or have a second parameter of type Object^ (for setters).

if (longMemberName == L"BlogDemoApp.SampleBindableClass.FullName")
{
  XamlMember^ xamlMember = ref new XamlMember(this, L"FullName", L"String");
  xamlMember->Getter =
  [](Object^ instance) -> Object^
  {
    auto that = (::BlogDemoApp::SampleBindableClass^)instance;
    return that->FullName;
  };

  xamlMember->Setter =
 [](Object^ instance, Object^ value) -> void
  {
    auto that = (::BlogDemoApp::SampleBindableClass^)instance;
    that->FullName = (::Platform::String^)value;
  };
  return xamlMember;
}

The two lambdas defined use the lambda ‘decay to pointer’ functionality to bind to Getter and Setter methods.  These function pointers can then be called by the data binding infrastructure, passing in an object instance, in order to set or get a property based on only its name.  Within the lambdas, the generated code adds the proper type casts in order to marshal to/from the actual types.

Final Linking and Final Thoughts

After compiling the xamltypeinfo.g.cpp file into xamltypeinfo.g.obj, we can then link this object file along with the other object files to generate the final executable for the program.  This executable, along with the winmd file previously generated, and your xaml files, are packaged up into the app package that makes up your Windows Store Application.

A note: the Bindable attribute described in this post is one way to enable data binding in WinRT, but it is not the only way.  Data binding can also be enabled on a class by implementing either the ICustomPropertyProvider interface or IMap<String^,Object^>.  These other implementations would be useful if the Bindable attribute cannot be used, particularly if you want a non-public class to be data-bindable.

For additional info, I recommend looking at this walkthrough, which will guide you through building a fully-featured Windows Store Application in C++/XAML from the ground up.  The Microsoft Patterns and Practices team has also developed a large application which demonstrates some best practices when developing Windows Store Applications in C++: project Hilo.  The sources and documentation for this project can be found at http://hilo.codeplex.com/.  (Note that this project may not yet be updated for the RTM release of Visual Studio.)

I hope this post has given you some insight into how user-edited files and generated files are compiled together to produce a functional (and valid) C++ program, and given you some insight into how the XAML data binding infrastructure actually works behind the scenes.

C++/CX Part 0 of [n]: An Introduction

$
0
0

Hello; I'm James McNellis, and I've recently joined the Visual C++ team as a libraries developer. My first encounter with the C++/CX language extensions was early last year, while implementing some code generation features for the Visual Studio 2012 XAML designer. I started off by hunting for some example code, and it suffices to say that I was a bit surprised with what I first saw. My initial reaction was along the lines of:

"What the heck are these hats doing in this C++ code?"

Actually, I was quite worried; because I thought it was C++/CLI—managed code. Not that managed code is bad, per se, but I'm a C++ programmer, and I had been promised native code.

Thankfully, my initial impression was uninformed and wrong: while C++/CX is syntactically similar to C++/CLI and thus looks almost the same in many ways, it is semantically quite different. C++/CX code is native code, no CLR required. Programming in C++/CLI can be very challenging, as one must deftly juggle two very different object models at the same time: the C++ object model with its deterministic object lifetimes, and the garbage-collected CLI object model. C++/CX is much simpler to work with, because the Windows Runtime, which is based on COM, maps very well to the C++ programming language.

Windows Runtime defines a relatively simple, low-level Application Binary Interface (ABI), and mandates that components define their types using a common metadata format. C++/CX is not strictly required to write a native Windows Runtime component: it is quite possible to write Windows Runtime components using C++ without using the C++/CX language extensions, and Visual C++ 2012 includes a library, the Windows Runtime C++ Template Library (WRL), to help make this easier. Many of the Windows Runtime components that ship as part of Windows (in the Windows namespace) are written using WRL. There's no magic in C++/CX: it just makes writing Windows Runtime components in C++ much, much simpler and helps to cut the amount of repetitive and verbose code that you would have to write when using a library-based solution like WRL.

The intent of this series of articles is to discuss the Windows Runtime ABI and to explain what really happens under the hood when you use the C++/CX language constructs, by demonstrating equivalent Windows Runtime components written in C++ both with and without C++/CX, and by showing how the C++ compiler actually transforms C++/CX code for compilation.

Recommended Resources

There are already quite a few great sources of information about C++/CX, and I certainly don't intend for a simple series of blog articles to replace them, so before we begin digging into C++/CX, I wanted to start with a roundup of those resources.

First, if you're interested in the rationale behind why the C++/CX language extension were developed and how the C++/CLI syntax ended up being selected for reuse, I'd recommend Jim Springfield's post on this blog from last year, "Inside the C++/CX Design". Also of note is episode 3 of GoingNative, in which Marian Luparu discusses C++/CX.

If you're new to C++/CX (or Windows Store app and Windows Runtime component development in general), and are looking for an introduction to building software with C++/CX, or if you're building something using C++/CX and are trying to figure out how to accomplish a particular task, I'd recommend the following resources as starting points:

  • Visual C++ Language Reference (C++/CX): The language reference includes a lot of useful information, including a C++/CX syntax reference with many short examples demonstrating its use. There's also a useful walkthrough of how to build a Windows Store app using C++/CX and XAML. If you're just starting out, this would be a great place to start.

  • C++ Metro style app samples: Most of the C++ sample applications and components make use of C++/CX and many demonstrate interoperation with XAML.

  • Component Extensions for Runtime Platforms: This used to be the documentation for C++/CLI, but it has since been updated to include documentation for C++/CX, with comparisons of what each syntactic feature does in each set of language extensions.

  • Hilo is an example application, written using C++, C++/CX, and XAML, and is a great resource from which to observe good coding practices—both for modern C++ and for mixing ordinary C++ code with C++/CX.

  • Building Metro style apps with C++ on MSDN Forums is a great place to ask questions if you are stuck.

Tools for Exploration

Often, the best way to learn about how the compiler handles code is to take a look at what the compiler outputs. For C++/CX, there are two outputs that are useful to look at: the metadata for the component, and the generated C++ transformation of the C++/CX code.

Metadata: As noted above, Windows Runtime requires each component to include metadata containing information about any public types defined by the component and any public or protected members of those types. This metadata is stored in a Windows Metadata (WinMD) file with a .winmd extension. When you build a Windows Runtime component using C++/CX, the WinMD file is generated by the C++ compiler; when you build a component using C++ (without C++/CX), the WinMD file is generated from IDL. WinMD files use the same metadata format as .NET assemblies.

If you want to know what types have been fabricated by the C++ compiler to support your C++/CX code, or how different C++/CX language constructs appear in metadata, it is useful to start by inspecting the generated WinMD file. Because WinMD files use the .NET metadata format, you can use the ildasm tool from the .NET Framework SDK to view the contents of a WinMD file. This tool doesn't do much interpretation of the data, so it can take some getting used to how it presents data, but it's very helpful nonetheless.

Generated Code: When compiling C++/CX code, the Visual C++ compiler transforms most C++/CX constructs into equivalent C++ code. If you're curious about what a particular snippet of C++/CX code really does, it's useful to take a look at this transformation.

There is a top-secret compiler option, /d1ZWtokens, which causes the compiler to print the generated C++ code that it generated from your C++/CX source. (Ok, this compiler option isn't really top secret: Deon Brewis mentioned it in his excellent //BUILD/ 2011 presentation, "Under the covers with C++ for Metro style apps." However, do note that this option is undocumented, and thus it is unsupported and its behavior may change at any time.)

The output is intended for diagnostic purposes only, so you won't be able to just copy and paste the output and expect it to be compilable as-is, but it's good enough to demonstrate how the compiler treats C++/CX code during compilation, and that makes this option invaluable. The output is quite verbose, so it is best to use this option with as small a source file as possible. The output includes any generated headers, including the implicitly included <vccorlib.h>. I find it's often best to use types and members with distinctive names so you can easily search for the parts that correspond to your code.

There are two other useful compiler options, also mentioned in Deon's presentation, which can be useful if you want to figure out how class hierarchies and virtual function tables (vtables) are laid out. The first is /d1ReportAllClassLayout, which will cause the compiler to print out the class and vtable layouts for all classes and functions in the translation unit. The other is /d1ReportSingleClassLayoutClyde which will cause the compiler to print out the class and vtable layouts for any class whose name contains "Clyde" (substitute "Clyde" for your own type name). These options are also undocumented and unsupported, and they too should only be used for diagnostic purposes.

Next Up...

In our next article (which will be the first "real" article), we'll introduce a simple C++/CX class and discuss how it maps to the Windows Runtime ABI.

C++ AMP Resources

$
0
0

Hopefully by now you have heard of C++ AMP. C++ AMP is a modern C++ library (plus a key new language feature) that ships with Visual Studio 2012 and it lets you take advantage of accelerators, such as the GPU, for compute purposes. Think data parallelism, but at a massive level, accelerated by powerful hardware. If you need more motivation on how using C++ AMP can speed up code, check out the nbody or the morph demo.

To follow the C++ AMP story, you should subscribe to the Parallel Programming in Native Code blog. Over the last year we have published (and updated for RTM) a number of Visual Studio sample projects, links to complementary open source libraries, and of course the C++ AMP open specification that any vendor can implement, so they can offer C++ AMP on other non-Microsoft platforms. If you have questions on C++ AMP, we welcome them at our MSDN forum.

 

In addition, this week we published on our blog two collections of links worth sharing more broadly

  1. Learn C++ AMP” is for you if you are a total C++ AMP newbie and have now decided to take the plunge.
  2. Present on C++ AMP” will help you give a presentation on C++ AMP, which I know some of you need to do even if you are not experts on a technology – we’ve got you covered.

 

Finally, if you already feel comfortable with C++ AMP, you can prove your skills and also win software and hardware by taking part in the C++ AMP coding contest.

C++/CX Part 1 of [n]: A Simple Class

$
0
0

See C++/CX Part 0 of [N]: An Introduction for an introduction to this series.

In this article we'll consider the basics of C++/CX by looking at a simple Windows Runtime class; we'll skim over some of the details, but don't worry: we'll come back and cover them in future posts. The code in this post is complete, though some namespace qualification is omitted for brevity; attached to this article is a Visual Studio solution containing the complete code for both the C++/CX and the WRL component, along with a simple test app that uses both.

Alright. Here's our simple class:

    public ref class Number sealed
    {
    public:
        Number() : _value(0) { }

        int  GetValue()          { return _value;  }
        void SetValue(int value) { _value = value; }

    private:
        int _value;
    };

This is a rather silly class, but it is sufficient to demonstrate some of the fundamentals of both C++/CX and Windows Runtime. Aside from the public ref and sealed in the class declaration, this class looks exactly like an ordinary C++ class. This is a good thing: our C++/CX code should look similar to similar C++ code, but should be sufficiently different that we (and the compiler!) can identify it as being different.

So, what does it really mean that this class is a sealed, public, ref class? A ref class is a reference type. Windows Runtime is built atop COM, and a Windows Runtime reference type is effectively a COM class type. Whenever we interact with a reference type object, we do so indirectly (by reference), via a pointer to an interface that the reference type implements. Since we never interact with a reference type by value, its implementation is opaque: so long as its existing interface remains unchanged, its implementation may be modified without affecting other components that depend on it (new functionality can be added, but not removed).

A public type is visible outside of the component that defines it, and other components may refer to and use this type. Types can also be private (which is the default); a private type can only be referred to from within the component that defines it. The Windows Metadata file for a C++/CX component only contains metadata for public types. There are fewer restrictions on private types than on public types because private types do not appear in metadata and thus are not constrained by some of the rules of Windows Runtime.

The sealed simply specifies that this class may not be used as a base class. Most public Windows Runtime types are sealed (currently, the only public types that may be unsealed are those derived from Windows::UI::Xaml::DependencyObject; these types are used by XAML apps).

The "Ref classes and structs (C++/CX)" page in the aforementioned Visual C++ Language Reference has a good roundup of other interesting facts about reference types.

Interfaces

I said above that whenever we interact with a reference type object, we do so via an interface that the reference type implements. You may have noticed that it looks like our Number class doesn't implement any interfaces: it has no base class list at all. Thankfully, the compiler is going to help us out here so that our Number class isn't useless.

The compiler will automatically generate an interface for our class, named __INumberPublicNonVirtuals. As its name suggests, this interface declares all of the public, nonvirtual member functions of our Number type. If we were to define this ourselves in C++/CX, it would look like so:

    public interface struct __INumberPublicNonVirtuals
    {
        int GetValue() = 0;
        void SetValue(int) = 0;
    };

The Number class is then transformed to declare this interface. If our class declared any new public virtual members (i.e., not overrides of base class virtual member functions) or any virtual or nonvirtual protected members, the compiler would generate interfaces for those as well.

Note that these automatically generated interfaces only declare members that aren't already declared by an interface that the class explicitly implements. So, for example, if we declared another interface:

    public interface struct IGetNumberValue
    {
        int GetValue() = 0;
    };

and defined our Number class as implementing this interface, the automatically generated __INumberPublicNonVirtuals would only define the SetValue member function.

Error Handling

In modern C++ code, exceptions are usually used for error reporting (not always, but they should be the default). A function is expected to return its result directly (as a return value) and throw an exception if a failure occurs. However, exceptions are not portable across different languages and runtimes; exception handling machinery varies quite a bit. Even within C++ code exceptions can be problematic, as different compilers may implement exceptions differently.

Since exceptions don't work well across different languages, Windows Runtime does not use them; instead, each function returns an error code (an HRESULT) indicating success or failure. If a function needs to return a value, the value is returned via an out parameter. This is the same convention used by COM. It's up to each language projection to translate between error codes and the natural error handling facility for that language.

There is overhead involved in catching and rethrowing exceptions, but the benefit is obvious even in simple scenarios involving interaction between components written in different languages. Consider, for example, a function in a C# component calling a function in a component implemented in C++/CX. The C++ code can throw an exception derived from Platform::Exception, and if the exception is not handled, it will be caught at the ABI boundary and translated into an HRESULT, which is returned to the C# code. The CLR will then translate the error HRESULT into a managed exception, which will be thrown for the C# code to catch.

The important thing is that both components--the C# component and the C++ component--get to handle errors naturally using exceptions, even though they use different exception handling machinery. We'll cover the details of which exceptions get translated at the C++/CX boundary, and how the translation takes place, in a future article (this topic is sufficiently complex that it warrants separate treatment). For the moment, it is sufficient to know that the translation happens automatically.

Member Functions

We've intentionally made our Number class very simple: neither GetValue nor SetValue can throw, and a call to either will therefore always succeed. We can therefore use them to demonstrate how the compiler transforms our C++/CX member functions into the real ABI functions. GetValue is a bit more interesting since it returns a value, so let's take a look at it:

    int GetValue()
    {
        return _value;
    }

The compiler will generate a new function with the correct ABI signature; for example,

    HRESULT __stdcall __abi_GetValue(int* result)
    {
        // Error handling expressly omitted for exposition purposes
        *result = GetValue();
        return S_OK;
    }

The wrapper function has an additional out parameter for the return value appended to the parameter list, and its actual return type is changed to HRESULT. Windows Runtime functions use the stdcall calling convention on x86, so the __stdcall annotation is required. By default, nonvariadic member functions ordinarily use the thiscall calling convention. (Calling convention annotations only really matter on x86; x64 and ARM each have a single calling convention.)

We've named our wrapper function __abi_GetValue; this is the name that the compiler gives to the function on the interface that it generates; in the class it uses a much longer name with lots of underscores to ensure that it doesn't conflict with any user-declared functions or functions inherited from other classes or interfaces. The name of the function doesn't matter at runtime, so it doesn't really matter what name the function has. At runtime, functions are called via vtable lookup, and since the compiler is generating the wrapper functions, it knows which function pointers to place into the vtables.

A wrapper is generated for our SetValue function following the same pattern, with the exception that no out parameter is added because it returns no value.

A Simple Class, without C++/CX

With what we've discussed so far, we already have enough information to implement our Number class using C++ with the help of WRL and without using C++/CX.

When using C++/CX, the C++ compiler will generate both the Windows Metadata (WinMD) file for the component and the DLL that defines all of the types. When we don't use C++/CX, we need to use IDL to define anything that needs to end up in metadata and use midlrt to generate a C++ header file and a Windows Metadata file from the IDL. For those experienced with COM, this should be quite familiar.

First, we need to define an interface for our Number type. This is equivalent to the __INumberPublicNonVirtuals interface that the compiler generated for us automatically when we were using C++/CX. Here, we'll just name our interface INumber:

    [exclusiveto(Number)]
    [uuid(5b197688-2f57-4d01-92cd-a888f10dcd90)]
    [version(1.0)]
    interface INumber : IInspectable
    {
        HRESULT GetValue([out, retval] INT32* value);
        HRESULT SetValue([in] INT32 value);
    }

Our INumber interface derives from the IInspectable interface. This is the base interface from which all Windows Runtime interfaces derive; in C++/CX, every interface implicitly derives from IInspectable.

We also need to define the Number class itself in the IDL file, because it is public and therefore needs to end up in the metadata file:

    [activatable(1.0), version(1.0)]
    runtimeclass Number
    {
        [default] interface INumber;
    }

The activatable attribute used here specifies that this class is default constructible. The details of how object construction works will be covered in a future article. For the moment, it's sufficient to know that this activatable attribute will generate the required metadata in the metadata file to report the Number class as default constructible.

And, that's all that is required in the IDL file. If you compare the WinMD file produced by this IDL file with the one produced for our C++/CX component, you'll see that they are largely the same: the interface has a different name, and there are a few extra attributes applied to types in the C++/CX component, but they are otherwise the same.

The class definition in C++ is straightforward:

    class Number : public RuntimeClass<INumber>
    {
        InspectableClass(RuntimeClass_WRLNumberComponent_Number, BaseTrust)

    public:
        Number() : _value(0) { }

        virtual HRESULT STDMETHODCALLTYPE GetValue(INT32* value) override
        {
            *value = _value;
            return S_OK;
        }

        virtual HRESULT STDMETHODCALLTYPE SetValue(INT32 value) override
        {
            _value = value;
            return S_OK;
        }

    private:
        INT32 _value;
    };

The RuntimeClass class template and the InspectableClass macro are both from WRL: together they handle much of the mundane, repetitive work to implement a Windows Runtime class. The RuntimeClass class template takes as its arguments a set of interfaces that the class will implement and it provides a default implementation of the IInspectable interface member functions. The InspectableClass macro takes as its arguments the name of the class and the trust level of the class; these are required to implement pieces of the IInspectable interface.

The two member functions are defined as is expected, given the discussion above: instead of directly using the __stdcall modifier, we use the STDMETHODCALLTYPE, which expands to __stdcall when using Visual C++ and the Windows headers, but could be changed to expand to something else if you were using a different compiler. You could also use the STDMETHOD macro.

Finally, because our Number type is default constructible, and because the default constructor is public, meaning that other components can create an instance of this class, we need to implement the logic required to enable other components to call the constructor of our class. This involves implementing a factory class and registering the factory so that we can return an instance of the factory when asked. There's a fair bit of work required here, but since we only have a default constructor, we can simply use the ActivatableClass macro from WRL:

    ActivatableClass(Number)

And, that's it! The WRL component requires a bit more than three times as much code as the C++/CX component, but this is just a small, simple component. As things get more complex, and as we use more features of Windows Runtime, we'll see that the WRL-based code both grows and becomes more complex much faster than the C++/CX-based code.

In our next post, we'll discuss hats (^) in detail, and in future posts we'll cover the details of construction, exception handling, and other interesting topics.

Viewing all 437 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>